Abstract Windowing Toolkit AWT
Abstract Windowing Toolkit AWT
AWT
Introduction
• Java AWT (Abstract Windowing Toolkit) is an API to develop
GUI or window-based application in java.
• Java AWT components are platform-dependent i.e. components
are displayed according to the view of operating system.
• AWT is heavyweight i.e. its components uses the resources of
system.
• The java.awt package provides classes for AWT API such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.
Events
Object
Object
ActionEvent
ActionEvent
EventObject
EventObject
AdjustmentEvent
AdjustmentEvent
AWTEvent
AWTEvent ContainerEvent
ContainerEvent
ItemEvent
ItemEvent
FocusEvent
FocusEvent
TextEvent
TextEvent
PaintEvent
PaintEvent
ComponentEvent
ComponentEvent
WindowEvent
WindowEvent
InputEvent
InputEvent
KeyEvent MouseEvent
KeyEvent MouseEvent
MouseWheelEvent
MouseWheelEvent
GUI
AWT Hierarchy
Object
• The Object class is the top most class and parent of all
the classes in java by default.
• Every class in java is directly or indirectly derived from
the object class.
Component
• The Component is abstract class that encapsulates all
the attributes of visual component.
• All User interface (UI) elements that are displayed on
screen are subclasses of Component.
Method Description
java.lang.Object
| +----java.awt.Component
| +----java.awt.Container
| +----java.awt.Panel
| +----java.applet.Applet
Window
• The window is the container that have no borders and
menu bars.
• You must use frame, dialog or another window for
creating a window.
Frame
• It is subclass of Window.
• The Frame is the container that contain title bar and
can have menu bars,borders, and resizing corners.
• It can have other components like button, textfield, etc.
• Methods:
• void setTitle(String title)
• void setBackground(Color bgcolor)
Working with Frame Window
• Extends Frame class
• Constructor are:
• Frame()
• Frame(String title)
• Setting and Getting window size:
• void setSize(int width, int height)
• void setSize(Dimension newsize)
• Showing and Hiding Frame
• void setVisible(boolean visibleFlag)
Frame Class
• We can create stand-alone AWT based applications.
• A Frame provides main window for the GUI application.
• There are two ways to create a Frame :
1.By instantiating Frame Class
2.By extending Frame class
Program using Frames
import java.awt.*;
class FirstFrame{ public static void main(String args[]){
• Methods
• void setText(String str)
• String getText( )
• void setAlignment(int how)
• int getAlignment( )
Controls
// Demonstrate Labels public LabelDemo()
import java.awt.*; {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
public class LabelDemo // add labels to applet window
extends Frame add(one);
{ add(two);
add(three);
}
}
Buttons
• The most widely used control is the push button.
• A push button is a component that contains a label and that
generates an event when it is pressed.
• Push buttons are objects of type Button.
• Button defines these two constructors:
• Button( )
• Button(String str)
Buttons
• String getLabel()
• void setLabel(String str)
• void setEnabled(Boolean enable)
• Void addActionListener(ActionListener l)
• void removeActionListener(ActionListener l)
• String getActionCommand()
• void setActionCommand(String Cmd)
Button yes, no, maybe;
// Demonstrate Buttons public ButtonDemo()
import java.awt.*; {
yes = new Button("Yes");
public class ButtonDemo extends no = new Button("No");
Frame maybe = new Button(“Understand");
{ add(yes);
String msg = ""; add(no);
add(maybe);
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}
}
Check Boxes
• A check box is a control that is used to turn an option on
or off.
• It consists of a small box that can either contain a check
mark or not.
• There is a label associated with each check box that
describes what option the box represents.
• We change the state of a check box by clicking on it.
Check boxes can be used individually or as part of a
group.
Checkbox constructors:
• Checkbox( )
• Checkbox(String str)
• Checkbox(String str, boolean on)
• Checkbox(String str, boolean on, CheckboxGroup cbGroup)
• Checkbox(String str, CheckboxGroup cbGroup, boolean on)
Methods
• boolean getState( )
• void setState(boolean on)
• String getLabel( )
• void setLabel(String str)
• void addItemListener(ItemListener l)
• void removeItemListener(ItemListener l)
public CheckboxDemo()
// Demonstrate check boxes. {
import java.awt.*; Win98 = new Checkbox("Windows 98/XP",
null, true);
winNT = new Checkbox("Windows
public class CheckboxDemo extends
NT/2000");
Frame solaris = new Checkbox("Solaris");
{ mac = new Checkbox("MacOS");
String msg = ""; add(Win98);
Checkbox Win98, winNT, solaris, mac; add(winNT);
add(solaris);
add(mac);
}
Checkbox Group
• It is possible to create a set of mutually exclusive
check boxes in which one and only one check box in
the group can be checked at any one time.
• These check boxes are often called radio button.
• Check box groups are objects of type
CheckboxGroup.
• Only the default constructor is defined, which creates
an empty group.
Methods
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox wh)
public CBGroup()
{
import java.awt.*; cbg = new CheckboxGroup();
public class CBGroup extends FrameWin98 = new Checkbox("Windows 98/XP", cbg,
{ true);
String msg = ""; winNT = new Checkbox("Windows NT/2000", cbg,
Checkbox Win98, winNT, false);
solaris, mac;
solaris = new Checkbox("Solaris", cbg,
CheckboxGroup cbg; false);
mac = new Checkbox("MacOS", cbg, false);
add(Win98); add(winNT);
add(solaris); add(mac);
}
Choice Controls
• The Choice class is used to create a pop-up list of items
from which the user may choose.
• Thus, a Choice control is a form of menu.
• Each item in the list is a string that appears as a left
justified label in the order it is added to the Choice
object.
Methods
void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
int getItemCount( )
void select(int index)
void select(String name)
String getItem(int index)
import java.awt.*;
os.add("Solaris");
public class ChoiceDemo extends os.add("MacOS");
Frame browser.add("Netscape 3.x");
{ browser.add("Netscape 4.x");
Choice os, browser; browser.add("Netscape 5.x");
String msg = ""; browser.add("Netscape 6.x");
public ChoiceDemo() browser.add("Internet Explorer 4.0");
{ browser.add("Internet Explorer 5.0");
os = new Choice(); browser.add("Internet Explorer 6.0");
browser = new Choice(); browser.add("Lynx 2.4");
os.add("Windows 98/XP"); browser.select("Netscape 4.x");
os.add("Windows NT/2000"); add(os);
add(browser);
}
Lists
• The List class provides a compact, multiple-choice,
scrolling selection list.
• Unlike the Choice object, which shows only the single
selected item in the menu, a List object can be
constructed to show any number of choices in the
visible Window.
• It can also be created to allow multiple selections.
List
• List( )
• List(int numRows)
• List(int numRows, boolean multipleSelect)
• The first version creates a List control that allows only one item to be
selected at any one time.
• In the second form, the value of numRows specifies the number of
entries in the list that will always be visible (others can be scrolled into
view as needed).
• In the third form, if multipleSelect is true, then the user may select two
or more items at a time.
Methods
void add(String name)
void add(String name, int index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
int getItemCount( )
void select(int index)
String getItem(int index)
ScrollBars
• Scroll bars are used to select continuous values
between a specified minimum and maximum.
• Scroll bars may be oriented horizontally or
vertically.
• A scroll bar is actually a composite of several individual
parts.
• slider box (or thumb) for the scroll bar.
• The slider box can be dragged by the user to a new
position, this action translates into some form of page
up and page down.
Constructors
• Scrollbar( )
• Scrollbar(int style)
• Scrollbar(int style, int iValue, int tSize, int min, int
max)
• The first form creates a vertical scroll bar.
• The second and third forms allow us to specify style
Scrollbar.VERTICAL, Scrollbar.HORIZONTAL.
• In the third form, the initial value of the scroll bar is passed
in iValue. The number of units represented by the height of
the thumb is passed in tSize. The minimum and maximum
values for the scroll bar are specified by min and max.
Methods
• TextField( )
• TextField(int numChars)
• TextField(String str)
• TextField(String str, int numChars)
TextField Methods
• String getText( )
• void setText(String str)
• String getSelectedText( )
• void select(int startIndex, int endIndex)
• boolean isEditable( )
• void setEditable(boolean canEdit)
• void setEchoChar(char ch)
• boolean echoCharIsSet( )
• char getEchoChar( )
TextArea
• Sometimes a single line of text input is not enough for
a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea.
• Following are the constructors for TextArea:
• TextArea( )
• TextArea(int numLines, int numChars)
• TextArea(String str)
• TextArea(String str, int numLines, int numChars)
• TextArea(String str, int numLines, int numChars,
int sBars)
interface
«interface»
ActionListener
ActionListener
interface
«interface»
AdjustmentListener
AdjustmentListener
interface
«interface»
ComponentListener
ComponentListener
interface
«interface»
ContainerListener
ContainerListener
interface
«interface»
FocusListener
FocusListener
interface
«interface» interface
«interface»
EventListener ItemListener
EventListener ItemListener
interface
«interface»
KeyListener
KeyListener
interface
«interface»
MouseListener
MouseListener
interface
«interface»
MouseMotionListener
MouseMotionListener
interface
«interface»
TextListener
TextListener
interface
«interface»
WindowListener
TextListener
Handling mouse events
• Event-listener interfaces for mouse events
• MouseListener
• MouseMotionListener
• Listen for MouseEvents
MouseListener and
MouseMotionListener interface methods
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Adapter example
• The window detects and shows where it is
clicked
Outline
MouseDetails.java
1 // Fig. 13.20: MouseDetails.java
2 // Demonstrating mouse clicks and distinguishing between mouse buttons.
Line 15
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class MouseDetails extends JFrame {
8 private int xPos, yPos;
9
10 // set title bar String; register mouse listener; size and show window
11 public MouseDetails()
12 {
13 super( "Mouse clicks and buttons" );
14
15 addMouseListener( new MouseClickHandler() ); Register mouse listener
16
17 setSize( 350, 150 );
18 setVisible( true );
19 }
20
21 // draw String at location where mouse was clicked
22 public void paint( Graphics g )
23 {
24 // call superclass paint method
25 super.paint( g );
26
Outline
MouseDetails.java
27 g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]",
28 xPos, yPos );
Line 41
29 }
30
31 public static void main( String args[] ) Lines 43-44
32 {
33 MouseDetails application = new MouseDetails(); Line 46
34 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
35 }
36 Line 48
37 // inner class to handle mouse events Invoke method mouseClicked
38 private class MouseClickHandler extends MouseAdapter { when user clicks mouseLine 51
39
40 // handle mouse click event and determine which button was pressed
41 public void mouseClicked( MouseEvent event )
Store mouse-cursor
42 {
43 xPos = event.getX();
coordinates where mouse was
44 yPos = event.getY(); clicked number of
Determine times
45 user has clicked mouse
46 String title = "Clicked " + event.getClickCount() + " time(s)";
47
48 if ( event.isMetaDown() ) // right mouse button
Determine if user
49 title += " with right mouse button"; clicked right mouse
50 button
Determine if user
51 else if ( event.isAltDown() ) // middle mouse button
52 title += " with center mouse button"; clicked middle mouse
button
Outline
MouseDetails.java
53
54 else // left mouse button
55 title += " with left mouse button";
56
57 setTitle( title ); // set title bar of window
58 repaint();
59
60 } // end method mouseClicked
61
62 } // end private inner class MouseClickHandler
63
64 } // end class MouseDetails
InputEvent methods that help distinguish among left-, center- and right-
mouse-button clicks
isAltDown() Returns true when the user clicks the middle mouse button on a
mouse with three buttons. To simulate a middle-mouse-button click
on a one- or two-button mouse, the user can press the Alt key on the
keyboard and click the only- or left-mouse button, respectively.
An Applet
• Applet is a public class which is predefined by
java.applet.Applet
• There is no main() method in Applet like
Application program. The main() method is
defined by browser or Appletviewer for Applet.
• Life cycle methods: init, start, paint, stop, destroy
• Applet is one type of container and subclass of
Panel.
Concepts of Applets
• Applets are small applications that are
accessed on an Internet server, import java.awt.*;
transported over the Internet, import java.applet.*;
automatically installed, and run as part public class SimpleApplet
extendsApplet {
of a Web document. public void paint(Graphics g) {
• After an applet arrives on the client, it g.drawString("A SimpleApplet",
has limited access to resources, so that it 20, 20); } }
can produce an arbitrary multimedia
user interface and run complex
computations without introducing the
risk of viruses or breaching data
integrity.
• applets – Java program that runs within
a Java-enabled browser, invoked
through an “applet” reference on a web
page, dynamically downloaded to the
client computer
There are two ways to run an applet:
• Executing the applet within a Java-compatible
Web browser, such as Netscape Navigator.
• Using an applet viewer, such as the standard JDK
tool, applet viewer.
• An applet viewer executes your applet in a
window. This is generally the fastest and easiest
way to test an applet.
• To execute an applet in a Web browser, you need
to write a short HTML text file that contains the
appropriate APPLET tag.
Differences between applets and applications
• Java can be used to create two types of programs:
applications and applets.
• An application is a program that runs on your computer,
under the operating system of that Computer(i.e an
application created by Java is more or less like one created
using C orC++).
• When used to create applications, Java is not much
different from any other computer language.
• An applet is an application designed to be transmitted
over the Internet and executed by a Java-compatible Web
browser.
• An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound
file, or videoclip.
• The important difference is that an applet is an
intelligent program, not just an animation or
media file(i.e an applet is a program that can
react to user input and dynamically change—not
just run the same animation or sound over and
over.
• Applications require main method to execute.
• Applets do not require main method.
• Java's console input is quite limited
• Applets are graphical and window-based.
Life cycle of an applet
Applets life cycle includes the following methods
• init()
• start( )
• paint( )
• stop( )
• destroy( )
When an applet begins, the AWT calls the following
methods, in this sequence: init( ) start( ) paint()
When an applet is terminated, the following
sequence of method calls takes place: stop( )
destroy( )
• init( ): The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
• start( ): The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Whereas init( ) is called once—the first time an applet is
loaded—start( ) is called each time an applet's HTML document is displayed onscreen.
So, if a user leaves a web page and comes back, the applet resumes execution at start(
).
• paint( ): The paint( ) method is called each time applet's output must be redrawn.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever
the applet must redraw its output, paint( ) is called. The paint( ) method has one
parameter of type Graphics. This parameter will contain the graphics context, which
describes the graphics environment in which the applet is running. This context is
used whenever output to the applet is required.
• stop( ): The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is
called, the applet is probably running. Applet uses stop( ) to suspend threads that
don't need to run when the applet is not visible. To restart start( ) is called if the user
returns to the page.
• destroy( ): The destroy( ) method is called when the environment determines that
your applet needs to be removed completely from memory. The stop( ) method is
always called before destroy( ).
Types of applets
• Applets are two types
oSimpleapplets
oJApplets
• Simple applets can be created by extending
Applet class
• JApplets can be created by extending JApplet
class of javax.swing.JApplet package
To create an applet
• import java.applet.*;
• Import java.awt.*;
• Applet tag code in comment.
• Extends Applet class
• Life cycle method
• Class must be public
Applet Life Cycle
Creating applets
Applets are created by extending the Applet
class.
import java.awt.*;
import java.applet.*; /* */
public classAppletSkel extends Applet{
publicvoid init() { // initialization }
publicvoid start() { // startorresume execution }
publicvoid stop() { // suspends execution }
publicvoid destroy() { // perform shutdownactivities }
publicvoid paint(Graphics g) { // redisplaycontents of window
}
}
passing parameters to applets
• APPLET tag in HTML allows you to pass
parameters to applet.
• To retrieve a parameter, use the getParameter( )
method. It returns the value of the specified
parameter in the form of a String object. // Use
Parameters
import java.awt.*;
importjava.applet.*; /* */
• public class ParamDemoextends Applet{
String fontName;
int fontSize;
Float leading;
boolean active; // Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName== null)
fontName= "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize =Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) { fontSize = -1; }
param = getParameter("leading");
try { if(param != null) // if notfound
leading = Float.valueOf(param).floatValue();
else leading = 0;
} catch(NumberFormatException e) { leading = -1; }
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue(); }
// Displayparameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("AccountActive: " + active, 0, 58);
}
}
Introduction to swings
• Swing is a set of classes that provides more powerful and
flexible components than are possible with the AWT.
• In addition to the familiar components, such as buttons, check
boxes, and labels, Swing supplies several exciting additions,
including tabbed panes, scroll panes, trees, and tables.
• Even familiar components such as buttons have more
capabilities in Swing.
• For example, a button may have both an image and a text
string associated with it. Also, the image can be changed as the
state of the button changes.
• Unlike AWT components, Swing components are not
implemented by platform-specific code.
• Instead, they are written entirely in Java and, therefore, are
platform independent.
• The term lightweight is used to describe such elements.
The Swing component are defined in javax.swing
1. AbstractButton: Abstract superclass for Swing buttons.
2. ButtonGroup: Encapsulates a mutually exclusive set of buttons.
3. ImageIcon: Encapsulates an icon.
4. JApplet: The Swing versionof Applet.
5. JButton: The Swing push button class.
6. JCheckBox: The Swing check box class.
7. JComboBox : Encapsulates a combo box (an combination of a drop-down
list and text field).
8. JLabel: The Swing versionof a label.
9. JRadioButton: The Swing versionof a radio button.
10. JScrollPane: Encapsulates a scrollable window.
11. JTabbedPane: Encapsulates a tabbed window.
12. JTable: Encapsulates a table-based control.
13. JTextField: The Swing versionof a text field.
14. JTree: Encapsulates a tree-based control.
Limitations of AWT
• AWT supports limited number of GUI
components.
• AWT components are heavyweight components.
• AWT components are developed by using
platform specific code.
• AWT components behaves differently in different
operating systems.
• AWT component is converted by the native code
of the operating system.
• Lowest Common Denominator
oIf not available natively on one Java platform,
not available on any Java platform
• Simple Component Set
• Components Peer-Based
oPlatform controls component appearance
oInconsistencies in implementations
oInterfacing to native platform error-prone
Event Handling Summary