jchap_12 use of applets in web documents, gui using awt & swing components(prof. ananda m...

20
Chapter –12: On Applets & Windows Programming with AWT and Swing 12.0 Int roduction 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 use rs throu gh the AWT (Abstract Window Toolkit) classes and not through the I/O classes. The A WT  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 acces s by outside codes mu st be ensured. Apple ts can be executed either within a Java-compatible Web browser or by the appletviewer which resid es as an essenti al part of the JDK. Rememb er that applet s do not need a main () method to start with. All appl et- progra ms mus t als o impor t  java.awt.* cla sses for win dow bas ed 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 A WT classes. Swing is a super char ged alter native to A WT . Swing provides mor e powe rful 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 ar e impl ement ed in pl at form-i nde pen dent codes, they ar e te rmed 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. JAppl et contain s 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

Upload: prof-dr-ananda-m-ghosh

Post on 30-May-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 1/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 installedand executed as part of a Web-document . Applets interact with the users through theAWT (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 classApplet . 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 beexecuted either within a Java-compatible Web browser or by the appletviewer whichresides 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 basedinteractions. 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) becomesessential 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 andflexible components than that are possible by AWT to provide. Swing componentsinclude buttons , check boxes , labels , scroll panes , tables , trees , etc. Since Swingcomponents are implemented in platform-independent codes, they are termed aslightweight.

The Swing related classes are contained in the javax.swing.* package. The foundationof Swing is the JApplet classes that are all derived from the Applet . JApplet containsmany rich functionality that are absent in Applet. However, we will study both to knowhow to write applets and windows programming using AWT and Swing classes andinterfaces.

12.1 Applets

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 2/20

An applet is a window-based program. Applets are event driven , that means, programwaits for some events to occur. The event-handler of AWT notifies the applet about anevent (say, mouse click ). Once this happens, the applet takes action and then returnscontrol 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 sourcecode (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 appletclasses;

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?

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 3/20

Picture 12.1

Take help of the appletviewer already present in the JDK. Click on the applet icon-boxwith 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 inappletviewer and press the ok button. The running applet will appear on your screenwith Applet marked on the left-top corner and Applet Started marked at the bottom-leftcorner (see picture 12.2). Press the left keys of the mouse on Applet menu and observethe drop-down menu items appearing then. Try to control the applet operations usingthose menu items.

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 4/20

Picture 12.2 Picture – 12.2 Picture – 12.2

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

12.2 Java’s Threads

For a repetitive work like repainting of a screen display, an applet will have totake help of thread s. Java provides support for multithreaded programming. What arethese threads?

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

Threads are lightweight, because they share the same address space, context switchingand inter-thread communication. So threads are always inexpensive. Threads can utilizethe idle time of a CPU in a much better way than what is possible by OS-processes.

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 5/20

The java run-time system depends on threads for many things – to makecomputing 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 programeither make use of extends Thread or implement Runnable interface. The Thread classhas 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 programthat 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

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 6/20

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 willnow try to know more about the basics of AWT.

12.3 AWT Basics

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 7/20

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 arevery often used in application programs.

Common windows are derived either from Panel or from Frame classes. Panelsare 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-basedwindows 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 anormal 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 arecalled. 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() {

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 8/20

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);

}}

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 9/20

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 inexample-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);

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 10/20

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() andpaint(). Then implement the windowClosing() method of theWindowListener interface.

• Create an object of the Frame subclass just derived. Make object visible bycalling the setVisible() method. You can also adjust the size by calling thesetSize() 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 awindow that may be the main or a child window of an applet, or a stand-alone applicationwindow. The origin of a window is taken at the top-left (0,0) corner and the coordinatesare specified in pixels. We will now see a demo-program of graphics use for different geometrical shapes andsizes 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>

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 11/20

</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 DrawBoxesapplet when paint() method is called. The drawRect() can display the outline of arectangle, whereas fillRect() can display a filled rectangle. Similar is the case withdrawOval() and fillOval(). The drawRoundRect() or fillRoundRect() methods candisplay 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 heigh t );void fillRoundRect ( int top , int left , int width , int heigh t , 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 bytop-left, and whose width and height are specified by width, height . For drawing acircle, 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(ColornewColour ) method. By default, graphics objects are drawn in the current foregroundcolour. 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

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 12/20

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 defaultlayout 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 Textediting Components will be used.

Controls are added to a window by creating first an instance of the desired controland then by calling the add() method of the Container . Any component can also beremoved 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.4when a push-button is pressed, an event signal is sent to the listener giving itsidentification for recognition. Each listener implements the ActionListener interfacewhere actionPerformed() method remains defined. An ActionEvent object is passed asthe 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>

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 13/20

*/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 Fieldsname = new TextField(15);

branch = new TextField(10);post = new TextField(10);salary = new TextField(10);

// creating Buttonsenter = new Button("Enter");clear = new Button("Clear");

// calling add() methods to include them in a windowadd(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 eventsname. 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

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 14/20

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 placedwithin the window container. Populate text-fields with data and see what happens whenyou press the Enter button . When you press the Clear button , the text-fields getcleared. 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 theaction-listener process.Once the action (i.e. pressing enter button after typing in the text fields) is taken, theaction-performed function gets triggered. The “enter” command repaints the window,whereas “clear” command erases the text fields as per instructions given within the

program.

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 15/20

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 AWTcomponents, 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 Swingcomponents 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>

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 16/20

</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 contpaneJRadioButton 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() andtwo JtextFields() swing components. “First, the content pane for the JApplet object isobtained and a flow layout is assigned as its layout manager.” Radio button pressgenerates the action event(s) that are handled by the actionPerformed() method. Whenthe radio button is pressed, the texts are displayed in the respective text fields. You canstart, 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 isimproving their supporting packages to reduce the programming burdens fromdevelopers.

Picture 12.6 (Reference Example 12.7)

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 17/20

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

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 18/20

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 panecPane.add(jp, BorderLayout.CENTER);

}

}

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

Picture 12.7 (Reference Example 12.8)

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 19/20

Tables get implemented by the Jtable class which has a constructor -- Jtable (Objectdata[][], Object colHeads[]); which has been used in this program. The data [][] is atwo-dimensional array of information placed row after row. The colHeads[] is a one-dimensional array containing the column names. For table creation, the following stepshave 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 columncan 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).

8/14/2019 Jchap_12 Use of Applets in Web Documents, GUI Using AWT & Swing Components(Prof. Ananda M Ghosh.)

http://slidepdf.com/reader/full/jchap12-use-of-applets-in-web-documents-gui-using-awt-swing-componentsprof 20/20

Java Beans can allow one to build complex systems from different softwarecomponents. It defines an architecture that specifies how different blocks can operatetogether. The Bean Developer Kit (BDK) is a tool, which can be downloaded fromJavaSoft 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 programmingusing heavyweight AWT and lightweight Swing component classes that are availablewithin the java and javax packages. Use of only a few components has beendemonstrated. There are many more useful components that can be found from the Java 2complete reference Manual. The same programming technique, which has been shownhere, can be applied for those components also.

Once the foundation concepts of java programming become clear to you, any complexsoftware 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, systemanalysis and design using UML chapter has been added with this book. The nextchapter devotes entirely on those topics.