You are on page 1of 20

Chapter –12:

On Applets & Windows Programming with AWT and Swing

12.0 Introduction

Applets are small java programs that are accessed from an Internet Server and installed
and executed as part of a Web-document. Applets interact with the users through the
AWT (Abstract Window Toolkit) classes and not through the I/O classes. The AWT
provides support for a window-based graphical interface.

Every applet that gets created for an application must be a subclass of the class
Applet. Therefore, all applets must import java.applet.* classes. Each applet must also
be declared as public as its access by outside codes must be ensured. Applets can be
executed either within a Java-compatible Web browser or by the appletviewer which
resides as an essential part of the JDK. Remember that applets do not need a main ()
method to start with.

All applet-programs must also import java.awt.* classes for window based
interactions. To view and test an applet, it is necessary to include the < applet > tags,
within the comment field at the head of a source code, as shown below: --

/*
< applet code = “ applet-name” width = value height = value>
</applet>
*/
where width and height specify the applet’s window size in pixel values.

Modern applications take help of windows programming to make man-


machine interactions more users friendly. Thus Graphic User Interfaces (GUI) becomes
essential for any kind of windows programming. In java, GUIs take help of AWT classes.

Swing is a supercharged alternative to AWT. Swing provides more powerful and


flexible components than that are possible by AWT to provide. Swing components
include buttons, check boxes, labels, scroll panes, tables, trees, etc. Since Swing
components are implemented in platform-independent codes, they are termed as
lightweight.

The Swing related classes are contained in the javax.swing.* package. The foundation
of Swing is the JApplet classes that are all derived from the Applet. JApplet contains
many rich functionality that are absent in Applet. However, we will study both to know
how to write applets and windows programming using AWT and Swing classes and
interfaces.

12.1 Applets
An applet is a window-based program. Applets are event driven, that means, program
waits for some events to occur. The event-handler of AWT notifies the applet about an
event (say, mouse click). Once this happens, the applet takes action and then returns
control to the AWT run-time system.

User interactions are sent to the applet as events to which the applet must respond.
Before we proceed with any further discussion, let us examine a simple applet source
code (example-12.1).

Example-12.1 A very simple Applet Source Code

import java.awt.*;
import java.applet.*;

// applet tag within comments for viewing & testing


/*
<applet code = "AmgApplet" width=200 height=150 >
</applet>
*/
// AmgApplet will be a subclass of the Applet superclass

public class AmgApplet extends Applet {


public void paint( Graphics gr) {
gr.drawString(" To Test an Applet.", 15, 15);
}
}

Note carefully: -- Two import statements used -- one each for java’s awt and applet
classes;
There is no main () method used;

paint () refers to an object gr of the class Graphics;

DrawString () method of gr-object is called.

Thus you are inheriting and utilizing different members (both data and methods)
of the awt and applet classes.

Compile the source code in the usual way.

Next question -- how to run this applet?


Picture 12.1

Take help of the appletviewer already present in the JDK. Click on the applet icon-box
with the right button of the mouse and select the Run Applet menu item. A new BlueJ:
Run Applet window will then appear (Picture 12.1). Choose Run Applet in
appletviewer and press the ok button. The running applet will appear on your screen
with Applet marked on the left-top corner and Applet Started marked at the bottom-left
corner (see picture 12.2). Press the left keys of the mouse on Applet menu and observe
the drop-down menu items appearing then. Try to control the applet operations using
those menu items.
Picture 12.2 Picture – 12.2 Picture – 12.2

An applet, as a general rule, writes to its window only when paint() or update() method
is called by the AWT. An applet can update its information to be displayed by calling the
repaint() method existing within AWT.

12.2 Java’s Threads

For a repetitive work like repainting of a screen display, an applet will have to
take help of threads. Java provides support for multithreaded programming. What are
these threads?

We know that a large program can be divided into some smaller parts that can run
concurrently. Each part of such a program is called a thread that can be defined as a
separate unit for execution. In a thread-based multitasking, two or more tasks of a
single program can proceed simultaneously. Multitasking threads need fewer overheads
than multitasking processes.

Threads are lightweight, because they share the same address space, context switching
and inter-thread communication. So threads are always inexpensive. Threads can utilize
the idle time of a CPU in a much better way than what is possible by OS-processes.
The java run-time system depends on threads for many things – to make
computing environment asynchronous, for preventing the waste of CPU cycles, etc.

12.2.1 The Thread Class & the Runnable Interface

Java’s multithreading system depends on the Thread class and the Runnable interface.

Thread encapsulates a thread of execution. To create a new thread, in your program


either make use of extends Thread or implement Runnable interface. The Thread class
has several methods for managing threads like -- run, sleep, start, getName,
getPriority, etc.

Execution of threads can be managed by the methods like – suspend(), resume(), stop(),
etc methods. Now be ready to see a demonstration of threads used in an applet program
that will display a scrolling banner (example-12.2).

Example=12.2 Use of Threads in an Applet programming

/**
* A scrolling banner applet
* making use of threads
* @author (Java 2 Reference)
**/
import java.awt.*;
import java.applet.*;
/*
<applet code ="BannerApplet" width=300 height=200>
</applet>
*/
public class BannerApplet extends Applet implements Runnable
{
String msg = " Java is moving around the World.";
Thread t = null;
int state;
boolean stopFlag;
// set colours and initialize thread
public void init() {
setBackground(Color.green);
setForeground(Color.red);
}
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// thread that runs the banner
public void run() {
char ch;
for ( ; ; ) {
try {
repaint();
Thread.sleep(300);
ch = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg += ch;
if(stopFlag)
break;
} catch (InterruptedException e) { }
}
}
// stop running
public void stop() {
stopFlag = true;
t = null;
}
// banner display

public void paint(Graphics gr) {


gr.drawString(msg, 100, 75);
}
}

Enter, compile and run this applet program with threads to see what happens.

Please note the following points: --

• After initialization, AWT calls start() method to start the applet running.
• The t.start() calls a method ( defined in Thread ) to cause run() to begin
execution.
• Inside the run(), the characters in the msg String are repeatedly rotated left.
• In each rotation, the repaint() is called and that in turn calls paint() method to
.display the current contents of msg.
• Between iterations, run() sleeps for 300 mSec.
• The stopFlag variable is checked after each iteration. When it becomes true,
the run() method terminates.

This example also shows how AWT controls the operations of an applet. We will
now try to know more about the basics of AWT.

12.3 AWT Basics


The AWT classes are contained in the java.awt package. The AWT classes like –
AWTEvent, BorderLayout, Button, Canvas, Checkbox, Choice, Color, Frame,
Graphics, Image, Menu, List, Panel, Rectangle, Scrollbar, TextArea, Window etc are
very often used in application programs.

Common windows are derived either from Panel or from Frame classes. Panels
are mostly used for applets, whereas Frames are used for stand-alone windows.

Panel is a window that does not contain a title bar, menu bar, or border. However,
by adding components -- positioning, re-sizing, etc can be implemented on panel-based
windows programming.

Frame encapsulates what is commonly known as “window”. It is a subclass of


Window containing title bar, menu bar, borders, resizing corners, etc. Frame creates a
normal window on the desktop. Frame window can also be created by an applet.

12.3.1 Handling Events in a Frame Window

Whenever an event (like mouse click, say) occurs in a window, the event handlers are
called. Each window handles its own events. It is possible to create stand-alone AWT
based application windows that can respond to both mouse-clicks and keystrokes.
Example-12.3 gives the demonstration of such a frame-based stand-alone window.

Example-12.3 Demonstration of a Frame Based Stand Alone Window

import java.awt.*;
import java.awt.event.*;

public class FrameWindow extends Frame


{
String keymsg = " when not pressed";
String mousemsg = " ";
int mouseX=40, mouseY=30;
//constructor
public FrameWindow() {
addKeyListener(new AmgKeyAdapter(this));
addMouseListener(new AmgMouseAdapter(this));
addWindowListener(new AmgWindowAdapter());
}
public void paint(Graphics gr) {
gr.drawString(keymsg, 50,50);
gr.drawString(mousemsg, mouseX, mouseY);
}
// start window program

public static void main() {


FrameWindow frwin = new FrameWindow();
frwin.setSize(new Dimension(300, 250));
frwin.setTitle("Example of AWT Based Application");
frwin.setVisible(true);
}
}
class AmgKeyAdapter extends KeyAdapter {
FrameWindow frWindow;
public AmgKeyAdapter(FrameWindow frWindow) {
this.frWindow = frWindow;
}
}

class AmgMouseAdapter extends MouseAdapter {


FrameWindow frWindow;
public AmgMouseAdapter( FrameWindow frWindow) {
this.frWindow = frWindow;
}
public void mousePressed(MouseEvent mouprs) {
frWindow.mouseX = mouprs.getX();
frWindow.mouseY = mouprs.getY();
frWindow.mousemsg = " Mouse is pressed at " + frWindow.mouseX +
", "+ frWindow.mouseY;
frWindow.repaint();
}
}

class AmgWindowAdapter extends WindowAdapter {

public void windowClosing(WindowEvent we) {


System.exit(0);
}
}
Picture 12.3

Run this program and see what happens whenever you press a mouse button at different
points on the window (Picture 12.3).

It is quite possible to create a frame-based window by an applet as demonstrated in


example-12.4.

Example-12.4 Creating a Frame Window within an Applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code ="AppletFrame" width=500 height=500>
</applet>
*/

class MyFrameWindow extends Frame


{ MyFrameWindow(String title) {
super(title);
MyWinAdapter winadpt = new MyWinAdapter(this);
addWindowListener(winadpt);
}

public void paint(Graphics gr) {


gr.drawString(" This is AMG's window", 300, 300);
}
}

class MyWinAdapter extends WindowAdapter {


MyFrameWindow myFrame;
public MyWinAdapter ( MyFrameWindow myFrame) {
this.myFrame = myFrame;
}
public void windowClosing( WindowEvent winev) {
myFrame.setVisible(false);
}
}

public class AppletFrame extends Applet {


Frame frm;
public void init() {
frm = new MyFrameWindow("AMG-Window");
frm.setSize(300, 300);
frm.setVisible(true);
}
public void start() {
frm.setVisible(true);
}
public void stop() {
frm.setVisible(false);
}
public void paint(Graphics gr) {

gr.drawString(" This is my applet window", 200, 200);


}
}

If you compile and run this program, you will observe that an applet creates a window,
called AMG-Window. Also note the following points in the program: --

• To create a frame window from within an applet, first create a subclass of


Frame and override the standard applet methods – init(), start(), stop() and
paint(). Then implement the windowClosing() method of the
WindowListener interface.
• Create an object of the Frame subclass just derived. Make object visible by
calling the setVisible() method. You can also adjust the size by calling the
setSize() method.
• The frame window is removed automatically when the applet is terminated.

12.2.2 Use of Graphics methods for Drawings

The AWT supports a good number of graphics methods for drawing lines, rectangles,
ellipses and circles, etc within a window frame. All graphics are drawn relative to a
window that may be the main or a child window of an applet, or a stand-alone application
window. The origin of a window is taken at the top-left (0,0) corner and the coordinates
are specified in pixels.

We will now see a demo-program of graphics use for different geometrical shapes and
sizes in an applet window (example-12.5).

Example-12.5 Demo of Graphics Use in an Applet

/**
* Write a description of class DrawBoxes here.
*/
import java.awt.*;
import java.applet.*;
/*
<applet code = "DrawBoxes" width=550 height=450>
</applet>
*/
public class DrawBoxes extends Applet
{
public void paint(Graphics gr) {
gr.drawRect(20, 20, 50, 50);
gr.fillRect ( 100, 20, 75, 50);
gr.fillRoundRect(80, 100, 150, 100, 30, 40);
gr.drawRoundRect(270, 70, 100, 75, 25, 25);
gr.drawOval( 200, 10, 60, 60);
gr.fillOval( 300, 150, 100, 75);
}
}

The subclass DrawBoxes, inherits from Applet superclass, makes use of a number of
drawing functions like drawRect(), fillRect(), drawRoundRect(), drawOval(), etc
which are member methods of the Graphics class. They are passed to the DrawBoxes
applet when paint() method is called. The drawRect() can display the outline of a
rectangle, whereas fillRect() can display a filled rectangle. Similar is the case with
drawOval() and fillOval(). The drawRoundRect() or fillRoundRect() methods can
display round cornered outline or filled rectangles respectively.
To call these methods arguments are to be passed. They are shown here: --

void drawRect( int top, int left, int width, int height);
void fillRoundRect( int top, int left, int width, int height, int xDiam, int yDiam);
where the diameters of the rounding arcs along the x and y axes are specified by
xDiam and yDiam respectively.

To draw an ellipse or a circle, drawOval() or fillOval() is used. The parameters to


be passed will be as follows: --

void drawOval(int top, int left, int width, int height);

the ellipse is drawn within a bounding rectangle whose upper-left corner is specified by
top-left, and whose width and height are specified by width, height. For drawing a
circle, the width-height should be the same.

Run the program and examine the output (Picture 12.4) for verification by yourself. For
drawing various shapes with colours, Graphics takes support of the setColor(Color
newColour) method. By default, graphics objects are drawn in the current foreground
colour. The change in colour can be done by calling setColor(..) method.

12.3.2 Use of AWT Controls

Controls are components that can allow a user to interact with an application in many
different ways using – Labels, Push buttons, Check boxes, List, Text editing, etc. A
built-in layout manager positions the components within a container window. The default
layout manager display components using left-to-right and top-to-bottom organization.
We will now study one example of AWT control where Labels, Push buttons and Text
editing Components will be used.

Controls are added to a window by creating first an instance of the desired control
and then by calling the add() method of the Container. Any component can also be
removed by calling the remove() method, if required. Except the passive control Labels,
all other AWT controls generate events when they are accessed by users. For example,

Picture 12.4
when a push-button is pressed, an event signal is sent to the listener giving its
identification for recognition. Each listener implements the ActionListener interface
where actionPerformed() method remains defined. An ActionEvent object is passed as
the argument to that method.
First decide how many control components are to be placed within the window.
Create instance for each one and call add() methods for inclusion. Activate listeners.
Write action-performed functions for different action-events.

Let us have a look at the example-12.6

Example 12.6 Demo of AWT Control Components

/* Write a description of class AwtControlDemo here.


* @author (your name)
• @version (a version number or a date) */

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code ="AwtControlDemo">
</applet>
*/
public class AwtControlDemo extends Applet
implements ActionListener
{
TextField name, branch, post, salary;
Button enter, clear;
String str = " ";
public void init() {
// creating Label instances
Label sname = new Label ("Name: ", Label.RIGHT);
Label sbranch = new Label (" Department: ", Label.RIGHT);
Label blank = new Label (" ");
Label epost = new Label ("Post: ", Label.RIGHT);
Label esalary = new Label ("Salary: ", Label.LEFT);
// creating Text Fields
name = new TextField(15);
branch = new TextField(10);
post = new TextField(10);
salary = new TextField(10);
// creating Buttons
enter = new Button("Enter");
clear = new Button("Clear");
// calling add() methods to include them in a window
add(sname);
add(name);
add(sbranch);
add(branch);
add(blank);
add(epost);
add(post);
add(esalary);
add(salary);
add(enter);
add(clear);
// activating Listeners for action events
name.addActionListener (this);
branch.addActionListener (this);
post.addActionListener (this);
salary.addActionListener(this);
enter.addActionListener(this);
clear.addActionListener(this);
}
// what actions are to be taken when action events occur
public void actionPerformed(ActionEvent ae) {
String act = ae.getActionCommand();
// when clear-button is pressed
if (act.equals("Clear")){

name.setText(" ");
branch.setText(" ");
post.setText(" ");
salary.setText(" ");
}
else if(act.equals("Enter")) // when enter-button is pressed
repaint();
}
// materials for painting
public void paint(Graphics gr) {
gr.drawString(" Name: " + name.getText(), 80,160);
gr.drawString(" Department: "+ branch.getText(), 80, 180);
gr.drawString(" Post Held: "+ post.getText(), 80, 200);
gr.drawString(" Last Salary: "+ salary.getText(),80,220);
}
}

Run this program using applet viewer and observe the components that are placed
within the window container. Populate text-fields with data and see what happens when
you press the Enter button. When you press the Clear button, the text-fields get
cleared. You can now enter a new set of data.

Try to understand the program, looking at the comments inserted at the appropriate
points. The initialized window waits for an action to be taken by a user by enabling the
action-listener process.
Once the action (i.e. pressing enter button after typing in the text fields) is taken, the
action-performed function gets triggered. The “enter” command repaints the window,
whereas “clear” command erases the text fields as per instructions given within the
program.
Picture 12.5 (Reference Example 12.6)

12.3 An Introduction to Swing

To build windows based applications, Swing is a better alternative to AWT. Swing


provides more powerful and flexible components. Over and above supporting all AWT
components, Swing makes addition of scroll panes, tabbed panes, trees, tables, etc.

Swing allows a button to have both an image and a text associated with it. Unlike AWT
components, Swing components are platform independent. That is why Swing
components are called lightweight.

The Swing package has a number of classes and interfaces. The Swing version of
Applet is called Japplet. The Swing version of Button, CheckBox, Label, ComboBox,
etc classes are defined in the name of Jbutton, JcheckBox, Jlabel, JcomboBox, etc.
Now have a look at a very simple Swing program (Example-12.7).
.
Example-12.7 A Simple Swing program using Radio Button and Text Fields

/*
* Write a description of a user-defined class SwingDemo here.
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; // including swing classes and interfaces
/*
<applet code="SwingDemo" width=250 height= 100>
</applet>
*/
public class SwingDemo extends JApplet implements ActionListener
{
JTextField jtf,jtf1,jtf2 ;
public void init() {
// get content pane
Container contpane = getContentPane();
contpane.setLayout(new FlowLayout() );

// add radio button to contpane


JRadioButton rb1 = new JRadioButton();
rb1.addActionListener(this);
contpane.add(rb1);

//create and add two text fields


jtf1 = new JTextField(15);
contpane.add(jtf1);
jtf2 = new JTextField(20);
contpane.add(jtf2);
}
public void actionPerformed(ActionEvent ae) {
jtf1.setText ("Use of Swing Component.");
jtf2.setText (" by --A.M.Ghosh.");
}
}

Run it using appletviewer and see what happens when you press the radio-button
(see Picture 12.6).

In the program, the content pane has been initialized first with one JradioButton() and
two JtextFields() swing components. “First, the content pane for the JApplet object is
obtained and a flow layout is assigned as its layout manager.” Radio button press
generates the action event(s) that are handled by the actionPerformed() method. When
the radio button is pressed, the texts are displayed in the respective text fields. You can
start, restart, or stop the applet by pressing appropriate applet menu-items.

You have been able to realize by this time that GUI based application development
becomes much simple when better support comes from the java packages. Thus java is
improving their supporting packages to reduce the programming burdens from
developers.

Picture 12.6 (Reference Example 12.7)


Now we will study another program (example-12.8) using Jtable component of
the Swing.

Example-12.8 Demo of the Jtable Component of the Swing Package

/*
* Write a description of class SwingTable here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.awt.*;
import javax.swing.*;

public class SwingTable extends JApplet


{
public void init(){
Container cPane = getContentPane(); // create a content pane
cPane.setLayout(new BorderLayout()); //set layout
// set column headings
final String[] colName = {"Book_Name", "Author", "Price_Rs."};
// table data
final Object[][] bdata = {
{"Core J2EE Patterns","Alur","395" },
{"Computer Security", "Bishop","450"},
{"E-Commerce", "Laudon","350"},
{"J2EE Tutorial","Bodoff","360"},
{"Building WEB Apps with UML","Conallen","250"},
{"XML & Java","Maruyama","350"},
{"The Java Programming Language","Arnold","295"},
{"Object Oriented Analysis & Design","Booch","450"},
{"The UML User Guide","Booch","415"},
{"Understanding OOP with Java","Budd","295"},
{"Java:How to Program","Deitel","350"},
{"Just Java 2","Van der Linden", "495"},
{"On to Java","Winston","180"},
{" Advanced Programming for Java2","Austin","375"},
{"Sams Teach Yourself Java2", "Cadenhead","250"},
{"Java Tutorial Continued","Campione","395"},
{"Thinking in Java","Eckel","495"},
{"Core Java 2-vol I & II","Horstmann","450+495"},
{"Java FAQs", "Kanerva", "260"},
{"Java 2 Network Security","Pistoia", "450"}
};
// create the table
JTable btable = new JTable(bdata, colName);
// add scroll pane when needed
int vrt = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int hrt = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

JScrollPane jp = new JScrollPane(btable,vrt,hrt);


// add scroll pane to content pane
cPane.add(jp, BorderLayout.CENTER);
}

Run this program using applet-viewer and observe that a table gets created with three
columns (with assigned headings) and as many number of rows as there are book-data
items (see Picture 12.7).

Picture 12.7 (Reference Example 12.8)


Tables get implemented by the Jtable class which has a constructor -- Jtable (Object
data[][], Object colHeads[]); which has been used in this program. The data [][] is a
two-dimensional array of information placed row after row. The colHeads[] is a one-
dimensional array containing the column names. For table creation, the following steps
have been followed: --

1) Jtable object is created first.


2) JscrollPane object is then created.
3) The table is added to the scroll pane.
4) The scroll pane is then added to the content pane of the applet, which was
created as the container of all components.

Just observe that the column boundaries can be resized by dragging the cursor. A column
can also be dragged to a new position also.

Swing is a large system and has many features that are worth exploring like -- toolbars,
progress bars, etc. Swing is just a part of the Java Foundation Classes (JFC).
Java Beans can allow one to build complex systems from different software
components. It defines an architecture that specifies how different blocks can operate
together. The Bean Developer Kit (BDK) is a tool, which can be downloaded from
JavaSoft site. Discussions on BDK have been kept out of scope from a beginner’s book
like this. Interested readers may contact the site – http://java.sun.com/ and collect many
more information from there.

12.4 Conclusion

This chapter has given an idea to the readers about java based windows programming
using heavyweight AWT and lightweight Swing component classes that are available
within the java and javax packages. Use of only a few components has been
demonstrated. There are many more useful components that can be found from the Java 2
complete reference Manual. The same programming technique, which has been shown
here, can be applied for those components also.

Once the foundation concepts of java programming become clear to you, any complex
software development problem can be tackled by you if you know how to identify the
problem domain objects/classes, and the interactions taking place between them to
produce the desired outputs for different users of the system. For that reason, system
analysis and design using UML chapter has been added with this book. The next
chapter devotes entirely on those topics.

You might also like