[go: up one dir, main page]

0% found this document useful (0 votes)
28 views78 pages

Chap4 1.awt

Chapter 4 discusses the Abstract Window Toolkit (AWT) in Java, which is used for developing GUI applications. It covers various components such as Frames, Panels, Buttons, Labels, and Checkboxes, detailing their methods and usage. The chapter also introduces event handling and the lifecycle of Applets, providing examples of how to implement these components in Java code.

Uploaded by

dhhdxhus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views78 pages

Chap4 1.awt

Chapter 4 discusses the Abstract Window Toolkit (AWT) in Java, which is used for developing GUI applications. It covers various components such as Frames, Panels, Buttons, Labels, and Checkboxes, detailing their methods and usage. The chapter also introduces event handling and the lifecycle of Applets, providing examples of how to implement these components in Java code.

Uploaded by

dhhdxhus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Chapter 4.

AWT, Swings and Event


Handling (16 marks)
Abstract Window Toolkit
AWT
Introduction
• Java AWT (Abstract Window 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.
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.

Component is responsible for remembering the current


foreground and background color and the currently
selected text font.
Methods of Component class

Method Description

public void add(Component c) inserts a component on this


component.
public void setSize(int width, int sets the size (width and height) of the
height) component.
public void setLayout(LayoutManager defines the layout manager for the
m) component.
public void setVisible(boolean status) changes the visibility of the component,
by default false.
void remove(Component c) Remove a component
void setBounds(int x,int y, int width, Set the location and size of single
int height) component and useful only with null
layout.
Container
• The Container is a component in AWT that can contain
another components like buttons, textfields, labels etc.
• The classes that extends Container class are known as
container such as Frame, Dialog and Panel.
• Container is responsible for laying out any
components that it contains through the use of layout
managers.
• Methods:
• void setFont(Font f)
sets the font of this container.
• void setLayout(LayoutManager mgr)
sets the layout manager for this container.
Panel
• Panel class is concrete class it doesn’t add new
methods.
• The Panel is the container that doesn't contain title
bar and menu bars and Borders.
• It can have other components like button, textfield etc.
Panel Example
import java.awt.*;
public class PanelDemo extends Frame {
PanelDemo(){
setTitle("Panel Demo");
Panel panel= new Panel();
panel.setBounds(40, 80, 200, 200);
panel.setBackground(Color.gray);
add(panel);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
PanelDemo p = new PanelDemo();
}
}
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.
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
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)
sets the title for this frame to the specified string.
• void setBackground(Color bgcolor)
sets the background color of this window.
Working with Frame Window
• Constructor are:
• Frame()
creates a standard window that does not contain a title
• Frame(String title)
creates a window with the title specified by the 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 (instantiating frame class)
import java.awt.*;
class FirstFrame{ public static void main(String args[]){
FirstFrame(){ FirstFrame f=new FirstFrame();
Frame f=new Frame(); }
Button b=new Button("click }me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
Program using Frames (extending frame
class)
public static void main
import java.awt.*; (String args[]){
class First extends Frame{ First f=new First();
First(){ }
}
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
Controls
• Labels
• Buttons
• Checkbox
• CheckboxGroup
• Textfield
• TextFieldArea
• ScollBar
Label
• The easiest control to use is a label.
• A label is an object of type Label, and it contains a
string, which it displays.
• Labels are passive controls that do not support any
interaction with the user.
Label

Label defines the following constructors:


• Label( )
The first version creates a blank label.
• Label(String str)
The second version creates a label that contains the string
specified by str. This string is left-justified.
• Label(String str, int how)
• The third version creates a label that contains the
string specified by str using the alignment specified by
how.
The value of how must be one of these three constants:
Label.LEFT, Label.RIGHT, or Label.CENTER.
Label
• Methods
1. void setText(String str): this method can be
used to modify the label’s text
2. String getText( ): this method is used to read
the label’s text.
3. void setAlignment(int how): this method is
used to modify the alignment of the text.
4. int getAlignment( ): this method is used to
retrieve the alignment of the text
Label Example
import java.awt.*; add(l1);
public class LabelDemo add(l2);
extends Frame { add(l3);
LabelDemo(String s) { }
super(s); public static void
setLayout(null); main(String args[]) {
setVisible(true); LabelDemo ld = new
setSize(500,300); LabelDemo("Demonstrating
Label l1 = new Label("One"); Label using Frame");
Label l2 = new Label(); }
l2.setText("Two"); }
Label l3 = new
Label("Three");
l1.setBounds(50, 50, 100,
100);
l2.setBounds(50, 150, 100,
100);
l3.setBounds(50, 250, 100,
100);
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( )
constructs a button with empty label
• Button(String str)
constructs the button with the given label
Button (methods)
• String getLabel()
get the label(caption) of this button object
• void setLabel(String str)
set the label of this button object
• void setEnabled(Boolean enable)
enable or disable this button. Disabled button can not be clicked.
• void addActionListener(ActionListener l)
adds action listener to receive action events from this button.
• void removeActionListener(ActionListener l)
remove the action listener registered.
• String getActionCommand()
returns the command name of theaction event fired by this
button.
• void setActionCommand(String Cmd)
set the command name for action event fired by this button.
Button (example)
import java.awt.*; System.out.println(cancel.getL
public class ButtonDemo abel());
extends Frame{ ok.setEnabled(false);
Button ok,cancel; add(ok);
ButtonDemo(String s){ add(cancel);
super(s);
setLayout(null);
setVisible(true); }
setSize(500,300); public static void main(String
ok = new Button("Ok"); args[]) {
cancel = new Button(); ButtonDemo b1 = new
cancel.setLabel("Cancel"); ButtonDemo("Demonstrating
ok.setBounds(50, 50, 50, Buttons");
50); }
cancel.setBounds(120, 50, }
100, 50);
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( )
creates a checkbox with an empty string for its label.
• Checkbox(String str)
creates a checkbox with the specified label.
• Checkbox(String str, boolean on)
creates a checkbox with the specified label and sets the
specified state(checked if true or unchecked if false).
• Checkbox(String str, boolean on, CheckboxGroup
cbGroup)
constructs a checkbox with the specified label, set to the
specified state and in the specified checkbox group(for radio
button).
• Checkbox(String str, CheckboxGroup cbGroup, boolean
on)
Checkbox Methods
• boolean getState( )
determines whether this checkbox is in the on or off state.
• void setState(boolean on)
sets the state of this checkbox to the specified state.
• String getLabel( )
returns the label of this checkbox
• void setLabel(String str)
sets this checkbox label to be the string argument.
• void addItemListener(ItemListener l)
registers item listener to receive events from this checkbox.
• void removeItemListener(ItemListener l)
removes the registered item listener.
Checkbox example
import java.awt.*; add(l1);
public class CheckboxDemo add(c1);
extends Frame{ add(c2);
CheckboxDemo(){ add(c3);
setSize(500,500); }
setVisible(true); public static void
setLayout(new FlowLayout()); main(String args[]){
Checkbox c1,c2,c3; CheckboxDemo cd = new
c1 = new Checkbox(); CheckboxDemo();
c1.setLabel("Java"); }
c2 = new Checkbox("C++"); }
c2.setState(true);
c3 = new
Checkbox("Python",true);
Label l1 = new
Label("Languages:");
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.
CheckBoxGroup Methods
Checkbox getSelectedCheckbox( )
Gets the checkbox component group currently
selected.
void setSelectedCheckbox(Checkbox wh)
Determines which checkbox component
selected group.
CheckBoxGroup(Radio Button) example
import java.awt.*; email = new
public class Checkbox("Email",cg,true);
CheckboxDemo extends phone = new
Frame{ Checkbox("Phone",cg,false)
CheckboxDemo(){ ;
setSize(500,500); msg = new
setVisible(true); Checkbox("Message",cg,true
setLayout(new );
FlowLayout()); add(l2);
Checkbox add(email);
email,phone,msg; add(phone);
CheckboxGroup cg = new add(msg);
CheckboxGroup(); }
public static void main(String
Label l2 = new args[]){
Label("Preferred CheckboxDemo cd = new
Contact:"); CheckboxDemo();
}
}
Choice Controls (OPTIONAL)
• 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.*;
import java.applet.*; os.add("Solaris");
/* os.add("MacOS");
<applet code="ChoiceDemo" browser.add("Netscape 3.x");
width=300 height=180> browser.add("Netscape 4.x");
</applet> browser.add("Netscape 5.x");
*/ browser.add("Netscape 6.x");
public class ChoiceDemo extends browser.add("Internet Explorer 4.0");
Applet browser.add("Internet Explorer 5.0");
{ browser.add("Internet Explorer 6.0");
Choice os, browser; browser.add("Lynx 2.4");
String msg = ""; browser.select("Netscape 4.x");
public void init() add(os);
{ add(browser);
os = new Choice(); }
browser = new Choice(); public void paint(Graphics g)
os.add("Windows 98/XP"); {}}
os.add("Windows NT/2000");
Lists (OPTIONAL)
• 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)
TextField

• The TextField class implements a single-line


text-entry area, called an edit control.
• Text fields allow the user to enter strings and
to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
• TextField is a subclass of TextComponent.
TextField Constructors
• TextField( )
creates a textfield object
• TextField(int numChars)
creates a textfield object with the no.of columns
• TextField(String str)
creates a textfield instance with the given initial
text string.
• TextField(String str, int numChars)
construct a textfield instancenwith the given initial
text with the number of columns.
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)

sBars must be one of these values:


SCROLLBARS_BOTH,
SCROLLBARS_NONE,SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY
Methods
• TextArea is a subclass of TextComponent.
• Therefore, it supports the getText( ), setText( ),
getSelectedText( ), select( ), isEditable( ), and
setEditable( ) methods as of TextField.
• TextArea adds the following methods:
• void append(String str)
• void insert(String str, int index)
• void replaceRange(String str, int startIndex, int
endIndex)
Layout Managers
• Layout means arranging the components within
the container.
• The task of lay outing can be done automatically by
the Layout manager.
• The layout manager is set by the void setLayout( )
method.
• If no call to setLayout() is made, then the default
layout manager is used.
• Whenever a container is resized (or sized for the
first time), the layout manager is used to position
each of the components within it.
• The setLayout( ) method has the following
general form:
• void setLayout(LayoutManager layoutObj)
• Here, layoutObj is a reference to the desired
layout manager.
• If we wish to disable the layout manager and
position components manually, pass null for
layoutObj.
LayoutManager
• LayoutManager is an interface that is
implemented by all the classes of layout managers.
There are following classes that represents the
layout managers:
• FlowLayout
• BorderLayout
• GridLayout
• CardLayout
• GridBagLayout
FlowLayout
• FlowLayout is the default layout manager for
Panel.
• FlowLayout implements a simple layout style,
which is similar to how words flow in a text
editor.
• Components are laid out from the upper-left
corner, left to right and top to bottom.
• When no more components fit on a line, the next
one appears on the next line.
• A small space is left between each component,
above and below, as well as left and right.
FlowLayout Constructors
• FlowLayout( )
• FlowLayout(int how)
• FlowLayout(int how, int horz, int vert)
• The first is default, which centers components and leaves
five pixels of space between each component.
• The second form lets us specify how each line is aligned.
Valid values for how are as follows:
• FlowLayout.LEFT
• FlowLayout.CENTER
• FlowLayout.RIGHT
• The third form allows us to specify the horizontal and
vertical space left between components
FlowLayout Methods
• int getAlignment()
• int getHgap()
• int getVgap()
• int setAlignment(int align)
• int setHgap(int hgap)
• int setVgap(int vgap)
public class FlowLayoutDemo {
Checkbox Win98, winNT, solaris, mac;
public static void main(String args[])
{
Frame f = new Frame();
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.setSize(600,600);
f.setVisible(true);
add(Win98); add(winNT);add(solaris);add(mac);
}}
BorderLayout
• The BorderLayout class implements a common
layout style for top-level windows.
• It has four narrow, fixed-width components at
the edges and one large area in the center.
• The four sides are referred to as
• north,
• south,
• east, and
• west.
• The middle area is called the center.
BorderLayout Constructors
• BorderLayout( )
• BorderLayout(int horz, int vert)

• The first form creates a default border layout.


• The second allows us to specify the horizontal
and vertical space left between components in
horz and vert, respectively.
BorderLayout
• BorderLayout defines the following constants that
specify the regions:
• BorderLayout.CENTER
• BorderLayout.SOUTH
• BorderLayout.EAST
• BorderLayout.WEST
• BorderLayout.NORTH
• To add components, we use these constants with the
following form of add( ), which is defined by
Container:
• void add(Component compObj, Object region);
• Here, compObj is the component to be added, and
region specifies where the component will be added.
public class BorderLayoutDemo {
Public static void main(String args[]) {
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(new Button("This is across the top."), BorderLayout.NORTH);
f.add(new Label("The footer message."), BorderLayout.SOUTH);
f.add(new Button("Right"), BorderLayout.EAST);
f.add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts himself to the world;\n" +
"the unreasonable one persists in trying to adapt the world to
himself.\n" +
"Therefore all progress depends on the unreasonable man.\n\n" + " -
George Bernard Shaw\n\n";
f.add(new TextArea(msg), BorderLayout.CENTER);
}
}
GridLayout
• GridLayout lays out components in a two-
dimensional grid.
• When we instantiate a GridLayout, we define the
number of rows and columns.
GridLayout constructors
• GridLayout( )
• GridLayout(int numRows, int numColumns )
• GridLayout(int numRows, int numColumns, int horz,
int vert)
• The first form creates a single-column grid layout.
• The second creates a grid layout with specified number of
rows and columns.
• Either numRows or numColumns can be zero.
• Specifying numRows as zero allows for unlimited-length
columns.
• Specifying numColumns as zero allows for unlimited-length
rows.
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init(){
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
} }}}
GridBagLayout
• Each GridBagLayout object maintains a dynamic
rectangular grid of cells, with each component
occupying one or more cells, called its display
area.
• Each component managed by a grid bag layout is
associated with an instance of GridBagConstraints
that specifies how the component is laid out
within its display area.
• For customize a GridBagConstraints object by
setting one or more of its instance variables:
• gridx, gridy: Specifies the cell at the upper left of
the component's display area, where the upper-left-
most cell has address gridx = 0, gridy = 0.
• gridwidth, gridheight: Specifies the number of cells
in a row (for gridwidth) or column (for gridheight)
in the component's display area. The default value
is 1.
• fill: Used when the component's display area is
larger than the component's requested size to
determine whether (and how) to resize the
component.
import java.awt.*;
import java.util.*;
import java.applet.Applet;
public class GridBagEx1 extends Applet {
protected void makebutton(String name,
GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
add(button);
}
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
makebutton("Button1", gridbag, c);
makebutton("Button2", gridbag, c);
makebutton("Button3", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER; //end row
makebutton("Button4", gridbag, c);
c.weightx = 0.0; //reset to the default
makebutton("Button5", gridbag, c); //another row
}
public static void main(String args[]) {
Frame f = new Frame("GridBag Layout Example");
GridBagEx1 ex1 = new GridBagEx1();
ex1.init(); f.add("Center", ex1); f.pack();
f.resize(f.preferredSize());
f.show(); }}
Menu Bars and Menus
• A menu bar displays a list of top-level menu
choices. Each choice is associated with a dropdown
menu.
• This concept is implemented in Java by the
following classes:
• MenuBar, Menu, and MenuItem.
• In general, a menu bar contains one or more Menu
objects. Each Menu object contains a list of
MenuItem objects. Each MenuItem object
represents something that can be selected by the
user.
• MenuBar Class Defines only default constructor.
• Menu Class Constructors
• Menu( )
• Menu(String optionName)
• Menu(String optionName, boolean removable)
• Here, optionName specifies the name of the menu
selection.
• Individual menu items constructors:
• MenuItem( )
• MenuItem(String itemName)
• MenuItem(String itemName, MenuShortcut
keyAccel)
Methods
• Disable or enable a menu item by using:
• void setEnabled(boolean enabledFlag)
• boolean isEnabled( )
• Label set and get using:
• void setLabel(String newName)
• String getLabel( )
• Checkable menu item by using a subclass of
MenuItem called CheckboxMenuItem. :
• CheckboxMenuItem( )
• CheckboxMenuItem(String itemName)
• CheckboxMenuItem(String itemName, boolean on)
Methods
• Status about checkable MenuItem:
• boolean getState( )
• void setState(boolean checked)
• For add MenuItem:
• MenuItem add(MenuItem item)
• For add MenuBar
• Menu add(Menu menu)
• To get Item from Menu:
• Object getItem( )
import java.awt.*;
class MenuExample menu.add(i1);
menu.add(i2); menu.add(i3);
{
submenu.add(i4);
MenuExample(){
submenu.add(i5);
Frame f= new Frame("Menu Example"); menu.add(submenu);
mb.add(menu);
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu menu=new Menu("Menu");
f.setSize(400,400);
Menu submenu=new Menu("Sub Menu"); f.setLayout(null);
f.setVisible(true);
MenuItem i1=new MenuItem("Item 1");
}
MenuItem i2=new MenuItem("Item 2");
public static void main(String
MenuItem i3=new MenuItem("Item 3");
args[]) {
MenuItem i4=new MenuItem("Item 4"); new MenuExample();
MenuItem i5=new MenuItem("Item 5"); } }

You might also like