Java/View Applet in a web browser

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Data Types, Variables,and Arrays
Operators
Packages, Classes, and Interfaces
Java Program
Modifiers
Control Statements
Exception Handling
Object Oriented Programming
Wrappers
Strings
Math
Arrays
Random Numbers
Date and Time
Regular Expressions
Java Collections
Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
RMI
Image, Audio, Video
GUI
Applets
* Introduction to Applets
* View Applet in a web browser
Internationalization
JDBC
Java and XML

In this chapter we will give you some more examples on applets so that you get proper confidence in building applets. In the last chapter we tried to explain what are applets and how to develop simple applets. In this chapter we will take up some complicated ones, with buttons, text boxes, labels etc.


Below applet has a button when clicked changes the background color the the applet canvas. As you can see the AppletButtonExample class implements ActionListener interface which have one method that has to be implemented in AppetButtonExample class. actionPerformed method works as a callback method. It is called be the AWT framework and not by the programmer. Programmer just defines the behaviour that what should when this method is called. actionPerformed method has one parameter which is of type ActionEvent. ActionEvent describes about the event and the source of event. In our case it will always be the Button object.

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
 
public class AppletButtonExample extends Applet implements ActionListener {
 
	Button button;
 
	private static final Color RED = new Color(255, 0, 0);
 
	private static final Color GREEN = new Color(0, 255, 0);
 
	private static final Color BLUE = new Color(0, 0, 255);
 
	private Color colorArray[] = { RED, GREEN, BLUE};
 
	private int currentColor = 0;
 
	public void init() {
 
		button = new Button("Click Me");
		add(button);
		button.addActionListener(this);
 
	}
 
	// this method should be implemented by the developer 
	// to give the behaviour to the button click. 
	public void actionPerformed(ActionEvent arg0) {
 
		Object obj = arg0.getSource();
		if(obj == button) {
			setBackground(colorArray[currentColor % 3]);
			currentColor++;
		}
	}
 
}

AppletButtonExample2 is little different from AppletButtonExample. Here user has the choice to select the background color he wishes to paint. In this example we have added three check boxes for Red, Green and Blue color. Whichever the user selects that will be the background color. We have kept default as red.

import java.applet.Applet;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class AppletButtonExample2 extends Applet implements ActionListener {
 
	Button button;
 
	CheckboxGroup radioGroup;
 
	Checkbox radioRed;
 
	Checkbox radioGreen;
 
	Checkbox radioBlue;
 
	private static final Color RED = new Color(255, 0, 0);
 
	private static final Color GREEN = new Color(0, 255, 0);
 
	private static final Color BLUE = new Color(0, 0, 255);
 
	private Color colorArray[] = { RED, GREEN, BLUE };
 
	private int currentColor = 0;
 
	/**
	 * This method initializes the instance variable and perform other
	 * intialization processes.
	 */
	public void init() {
 
		button = new Button("Click Me");
 
		radioGroup = new CheckboxGroup();
		radioRed = new Checkbox("Red", radioGroup, true);
		radioGreen = new Checkbox("Green", radioGroup, false);
		radioBlue = new Checkbox("Blue", radioGroup, false);
		add(button);
		add(radioRed);
		add(radioGreen);
		add(radioBlue);
		button.addActionListener(this);
	}
 
	public void paint(Graphics g) {
 
                // check which color has been selected.
		if (radioRed.getState())
			setBackground(RED);
		if (radioGreen.getState())
			setBackground(GREEN);
		if (radioBlue.getState())
			setBackground(BLUE);
	}
 
	// this method should be implemented by the developer
	// to give the behaviour to the button click.
	public void actionPerformed(ActionEvent arg0) {
 
		Object obj = arg0.getSource();
		if (obj == button) {
			repaint(); // calling the paint method.
		}
	}
 
}


TextFieldAndListExample is an example where we have used a TextField, List and a Button. This applet will show a list box that will contain three values "RED", "GREEN" and "BLUE". User will select a value let us say "GREEN" and clicks on the button. The applet background will be changed to green and the text field will contain the value "GREEN".

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.List;
 
 
public class TextFieldAndListExample extends Applet implements ActionListener {
 
	List list;
 
	TextField field;
 
	Button button;
 
	private static final Color RED = new Color(255, 0, 0);
 
	private static final Color GREEN = new Color(0, 255, 0);
 
	private static final Color BLUE = new Color(0, 0, 255);
 
 
	public void init() {
		list = new List();
		list.add("RED");
		list.add("GREEN");
		list.add("BLUE");
		add(list);
		button = new Button("Finalize Color");
		button.addActionListener(this);
		field = new TextField(5);
 
		add(button);
		add(field);
	}
 
	public void actionPerformed(ActionEvent arg0) {
 
		Object source = arg0.getSource();
		if(source == button) {
		    String selectedText = list.getSelectedItem();
			field.setText(selectedText);
			if(selectedText.equals("RED")) {
				setBackground(RED);
			} else if (selectedText.equals("GREEN")) {
				setBackground(GREEN);
			} else {
				setBackground(BLUE);
			}
		}
	}
 
 
}
Applet Tag

As we have discussed earlier in the Applet Section that we need the APPLET tag to start an applet both from an HTML document and also from an applet viewer. The syntax for standard APPLET tag is

  < APPLET [CODEBASE = codebaseURL] CODE = appletFile
           [ALT = alternateText] [NAME = appletInstanceName]
           WIDTH = pixels HEIGHT = pixels [ALIGN = alignment]
           [VSPACE = pixels] [HSPACE = pixels]
  >
      [< PARAM NAME = AttributeName VALUE = AttributeValue>]
      [< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
      . . .
      [HTML Displayed in the absence of Java]
  </APPLET>

We will talk about each of them in detail now:

1. CODEBASE : This is an optional attribute which is used to mention the base URL of the applet code. This acts as the directory which will be searched for the applet’s executable class file. The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified.

2. CODE : This attribute is used to give the name of the file which contains the applet complied.class file .

3. ALT : This tag is used to specify a short text message that needs to be displayed if the browser understands the APPLET tag but can’t currently run Java applets. It is also an optional attribute.

4. NAME : Name as it suggest , it is used to specify a name for the applet instance. The Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface. It is also an optional attribute.

5. WIDTH AND HEIGHT : These attributes are needed to give the size (in pixels) of the applet display area.

6. ALIGN: This attribute defines the alignment of the applet. It is also an optional attribute.

7. VSPACE AND HSPACE : VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet. They are also the optional attributes.

8. PARAM NAME AND VALUE : The PARAM tag allows to specify appletspecific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

9. HANDLING OLDER BROWSERS : The best way to design the HTML page to deal with older browsers is to include HTML text and markup within the <applet></applet> tags. If the applet tags are not recognized by the browser, we will see the alternate markup. If Java is available, it will consume the entire markup between the <applet></applet> tags and disregard the alternate markup.

Here’s the HTML to start an applet called SampleApplet in Java and to display a message in older browsers:


 <applet code="SampleApplet" width=200 height=40>
   If we have a Java powered browser, we'd see & quote; 
   A Sample Applet &quote; here.<p>
 </applet>

Passing parameters to Applets

WE can pass the parameters to the applet with the help of APPLET tag in HTML. We can use getParameter( ) to get the value fo a specified parameter in the form of a String Object and we will have to convert them into numeric and Boolean form if required.

Here is an example that demonstrates passing parameters:

Code for ParameterPassingExample.java

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
 
public class ParameterPassingExample extends Applet {
 
	private String strToDisplay;
 
	public void init() {
		// getParameter method gets the value of the param by name
		// that has been passed in the applet tag in the html page.
		strToDisplay = getParameter("STR_TO_DISPLAY");
	}
 
	public void paint(Graphics g) {
 
		Color bgcolor = new Color(0, 255, 0); // green
 
		Color border = new Color(0, 0, 0); // black
 
		Color fgcolor = new Color(255, 0, 0); // red
 
		setBackground(bgcolor);
		setForeground(fgcolor);
		g.draw3DRect(20, 20, 200, 100, true);
		g.drawString(strToDisplay, 90, 70);
	}
}

Code for applet.html

<applet code="ParameterPassingExample" codebase="." width="250" height="150">
<param name="STR_TO_DISPLAY" value="MESHPLEX">
</applet>
getDocumentBase( ) and getCodeBase( )

We sometimes need to load media and Text with the help of Applets. We have the facility to load the data from the directory which holds the HTML file which started the applet and the directory from which the applet’s class loaded. These directories are returned in the form of URL by getDocumnetBase ( ) and getCodeBase ( ) methods.

AppletContext and ShowDocument ( )

AppletContext is an interface which helps us to get the required information from the environment in which the applet is running and getting executed. This information is derived by getAppletContext ( ) method which is defined by Applet. Once we get the information with the above mentioned method , we can easily bring another document into view by calling showDocument ( ) method. The basic functionality of this method is that it returns no value and never throw any exception even if it fails hence needed to be implemented with utmost care and caution.

There are two showDocument( ) methods.

1. The method showDocument(URL) displays the document at the specified URL.

2. The method showDocument(URL, where) displays the specified document at the specified location within the browser window.


Previous Next