24.1 What Is an Applet?

24.1 What Is an Applet?

PART 24

Java Applets

24.1 What is an Applet?

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API. There are some important differences between an applet and a standalone Java application, including the following:

  • An applet is a Java class that extends the java.applet.Applet class.
  • A main() method is not invoked on an applet, and an applet class will not define main().
  • Applets are designed to be embedded within an HTML page.
  • When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
  • A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
  • The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.

24.2 Advantages of Applets

There are many advantages of applet. They are as follows:

  • It works at client side so less response time.
  • Secured
  • Automatically integrated with HTML; hence, resolved all installation issues.
  • It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.
  • Can provide dynamic, graphics capabilities and visualizations

24.3 Drawbacks of Applets

  • Plugin is required at client browser to execute applet.
  • Applets can’t run any local executable programs
  • Applets can’t read/write to local computer’s file system
  • Applets can’t find any information about the local computer
  • All java created pop-up windows carry a warning message
  • Performance directly depend on client’s machine

24.4 Life Cycle of an Applet:

Four methods in the Applet class give you the framework on which you build any serious applet:

  • init:This method is intended for whatever initialization is needed for your applet.
  • start:This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.
  • paint:Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser.
  • stop:This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.
  • destroy:This method is only called when the browser shuts down normally.

"Hello, World" Applet:

The following is a simple applet named HelloWorldApplet.java:

importjava.applet.*;

importjava.awt.*;

publicclassHelloWorldAppletextendsApplet

{

publicvoidpaint(Graphics g)

{

setBackground(Color.GREEN);

g.drawString("Hello World",25,50);

}

}

Applet CLASS:

Every applet is an extension of thejava.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.

24.5 Invoking an Applet:

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet:

<html>

titleHello World Applet</title

appletcode="HelloWorldApplet.class"width="320"height="120"

</applet

</html>

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with a </applet> tag.

  • Enabling Local Applets to run in the Browsers

You have to install 32 bit JRE to run your applets within the Web Browsers.

64 bit java versions does not support Browser Plug-in Integration.

Use the following settings:

Java Security tab

24.6 Specifying Applet Parameters:

The following example demonstrates how to make an applet respond to setup parameters specified in the document.

The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string).

importjava.applet.*;

importjava.awt.*;

publicclassappletParameterextendsApplet{

privateStringstrDefault = "Hello! Java Applet.";

publicvoidpaint(Graphics g) {

StringstrParameter = getParameter("Message");

if (strParameter == null)

strParameter = strDefault;

setBackground(Color.GREEN);

g.drawString(strParameter, 50, 25);

}

}

The following is an example of an HTML file with an appletParameter.class embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag.

<html>

titleApplet Test</title

<h1> This is theapplet:</h1>

appletcode="appletParameter.class"width="800"height="100"

<paramname="message"value="This is HTML parameterText."

</applet

</html>

Note:Parameter names are not case sensitive.

24.7 Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

  1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
  2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
  3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height.
  4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
  5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height.
  6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
  7. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
  8. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
  9. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
  10. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.

Example of Graphics in applet:

importjava.applet.Applet;

importjava.awt.*;

publicclassGraphicsDemoextendsApplet{

publicvoidpaint(Graphics g) {

g.setColor(Color.red);

g.drawString("Welcome", 50, 50);

g.drawLine(20, 30, 20, 300);

g.drawRect(70, 100, 30, 30);

g.fillRect(170, 100, 30, 30);

g.drawOval(70, 200, 30, 30);

g.setColor(Color.green);

g.fillOval(170, 200, 30, 30);

g.drawArc(90, 150, 30, 30, 30, 270);

g.fillArc(270, 150, 30, 30, 0, 180);

}

}

24.8 Using SWING GUI in Applets: JApplet

JApplet — a class that enables applets to use Swing components. JApplet is a subclass of java.applet.Applet.

Any applet that contains Swing components must be implemented with a subclass of JApplet. If you're looking to use Swing components inside of your applet, JApplet would give you that functionality.

WindowBuilder plugin could bu used to create JApplet Application:

Here is a sample Hello World JApplet Example:

importjavax.swing.JApplet;

importjavax.swing.JButton;

importjavax.swing.JTextField;

importjava.awt.event.ActionListener;

importjava.awt.event.ActionEvent;

publicclassswappletextendsJApplet{

privatefinalJButtonbtnNewButton = newJButton("Say Hello");

privatefinalJTextFieldtextField = newJTextField();

publicswapplet() {

textField.setBounds(42, 52, 119, 20);

getContentPane().setLayout(null);

btnNewButton.addActionListener(newActionListener() {

publicvoidactionPerformed(ActionEventarg0) {

textField.setText("HelloApplet!");

}

});

btnNewButton.setBounds(220, 51, 114, 23);

getContentPane().add(btnNewButton);

getContentPane().add(textField);

}

}

PART 25

Other Network Applications

25.1 Sending E-mail

To send an email using your Java Application is simple enough but to start with you should have JavaMail API installed on your machine.

  • You can download latest version ofJavaMailfrom Java's standard website.

Download and unzip files, you will find a number of jar files for both the applications. You need to addmail.jar files in your CLASSPATH (In Eclipse drag and drop into src folder, right click mail.jar and select Build Path-> Add to Build Path)

Here is an example to send a simple email via GOOGLEGMAIL SMTP SERVER. Here it is assumed that yourlocalhost is connected to the internet and capable enough to send an email.

importjava.util.*;

importjavax.mail.*;

importjavax.mail.internet.*;

publicclassSendEmail{

publicstaticvoid main(String[] args) {

// Sender'semail ID needsto be mentioned

Stringfrom = "";

Stringpass = "123456";

// Recipient'semail ID needsto be mentioned.

Stringto = "";

Stringhost = "smtp.gmail.com";

// Getsystemproperties

Propertiesproperties = System.getProperties();

// Setup mail server

properties.put("mail.smtp.starttls.enable", "true");

properties.put("mail.smtp.host", host);

properties.put("mail.smtp.user", from);

properties.put("mail.smtp.password", pass);

properties.put("mail.smtp.port", "587");

properties.put("mail.smtp.auth", "true");

// GetthedefaultSessionobject.

Sessionsession = Session.getDefaultInstance(properties);

try{

// Create a defaultMimeMessageobject.

MimeMessagemessage = newMimeMessage(session);

// Set From: headerfield of theheader.

message.setFrom(newInternetAddress(from));

// Set To: headerfield of theheader.

message.addRecipient(Message.RecipientType.TO, newInternetAddress(to));

// Set Subject: headerfield

message.setSubject("This is theSubjectLine!");

// Now set theactualmessage

message.setText("This is actualmessage");

// Sendmessage

Transport transport = session.getTransport("smtp");

transport.connect(host, from, pass);

transport.sendMessage(message, message.getAllRecipients());

transport.close();

System.out.println("Sent messagesuccessfully....");

}catch (MessagingExceptionmex) {

mex.printStackTrace();

}

}

}