SlideShare a Scribd company logo
Abstract Windowing
Toolkit AWT(12 Marks)
Miss.P.S.Dungarwal
Lecturer in CM Department.
SHHJB Polytechnic, Chandwad.
1
Miss.P.S.Dungarwal
Advance Java Programming(22517)
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.
2
Miss.P.S.Dungarwal
GUI
3
Miss.P.S.Dungarwal
AWT HIERARCHY
4
Miss.P.S.Dungarwal
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.
5
Miss.P.S.Dungarwal
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.
6
Miss.P.S.Dungarwal
METHODS OF COMPONENT CLASS
Method Description
public void add(Component c) inserts a component on this
component.
public void setSize(int width, int
height)
sets the size (width and height) of the
component.
public void setLayout(LayoutManager
m)
defines the layout manager for the
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,
int height)
Set the location and size of single
component and useful only with null
layout. 7
Miss.P.S.Dungarwal
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)
• void setLayout(LayoutManager mgr)
8
Miss.P.S.Dungarwal
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.
9
Miss.P.S.Dungarwal
AN APPLET IS PANEL IS A CONTAINER
java.lang.Object
| +----java.awt.Component
| +----java.awt.Container
| +----java.awt.Panel
| +----java.applet.Applet
10
Miss.P.S.Dungarwal
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.
11
Miss.P.S.Dungarwal
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
12
Miss.P.S.Dungarwal
APPLET LIFE CYCLE
13
Miss.P.S.Dungarwal
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.
14
Miss.P.S.Dungarwal
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)
15
Miss.P.S.Dungarwal
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)
16
Miss.P.S.Dungarwal
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
17
Miss.P.S.Dungarwal
PROGRAM USING FRAMES
import java.awt.*;
class FirstFrame{
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); }
public static void main(String args[]){
FirstFrame f=new FirstFrame();
}
}
18
Miss.P.S.Dungarwal
PROGRAM USING FRAMES
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main
(String args[]){
First f=new First();
}
}
19
Miss.P.S.Dungarwal
CONTROLS
 Labels
 Buttons
 Checkbox
 CheckboxGroup
 Textfield
 TextFieldArea
 ScollBar
20
Miss.P.S.Dungarwal
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.
21
Miss.P.S.Dungarwal
LABELS
• Label defines the following constructors:
• Label( )
• Label(String str)
• Label(String str, int how)
• The first version creates a blank label.
• The second version creates a label that contains the string
specified by str. This string is left-justified.
• 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.
22
Miss.P.S.Dungarwal
LABEL
Methods
void setText(String str)
String getText( )
void setAlignment(int how)
int getAlignment( )
23
Miss.P.S.Dungarwal
CONTROLS
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo"
width=300 height=200>
</applet>
*/
public class LabelDemo extends
Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}
24
Miss.P.S.Dungarwal
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)
25
Miss.P.S.Dungarwal
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)
26
Miss.P.S.Dungarwal
// Demonstrate Buttons
import java.awt.*;
import java.applet.*;
/*
<applet code="ButtonDemo"
width=250 height=150>
</applet>
*/
public class ButtonDemo extends
Applet
{
String msg = "";
Button yes, no, maybe;
public void init()
{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button(“Understand");
add(yes);
add(no);
add(maybe);
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}
}
27
Miss.P.S.Dungarwal
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.
28
Miss.P.S.Dungarwal
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)
29
Miss.P.S.Dungarwal
METHODS
 boolean getState( )
 void setState(boolean on)
 String getLabel( )
 void setLabel(String str)
 void addItemListener(ItemListener l)
 void removeItemListener(ItemListener l)
30
Miss.P.S.Dungarwal
// Demonstrate check boxes.
import java.awt.*;
import java.applet.*;
/*
<applet code="CheckboxDemo"
width=250 height=200>
</applet>
*/
public class CheckboxDemo extends
Applet
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
public void init()
{
Win98 = new Checkbox("Windows 98/XP",
null, true);
winNT = new Checkbox("Windows
NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
add(Win98);
add(winNT);
add(solaris);
add(mac);
}
public void paint(Graphics g)
{}
}
31
Miss.P.S.Dungarwal
32
Miss.P.S.Dungarwal
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.
33
Miss.P.S.Dungarwal
METHODS
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox wh)
34
Miss.P.S.Dungarwal
import java.awt.*;
import java.applet.*;
/*
<applet code="CBGroup"
width=250 height=200>
</applet>
*/
public class CBGroup extends Applet
{
String msg = "";
Checkbox Win98, winNT,
solaris, mac;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP",
cbg, true);
winNT = new Checkbox("Windows NT/2000",
cbg, false);
solaris = new Checkbox("Solaris", cbg,
false);
mac = new Checkbox("MacOS", cbg,
false);
add(Win98); add(winNT);
add(solaris); add(mac);}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg +=
cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}}
35
Miss.P.S.Dungarwal
36
Miss.P.S.Dungarwal
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.
37
Miss.P.S.Dungarwal
METHODS
void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
int getItemCount( )
void select(int index)
void select(String name)
String getItem(int index)
38
Miss.P.S.Dungarwal
import java.awt.*;
import java.applet.*;
/*
<applet code="ChoiceDemo"
width=300 height=180>
</applet>
*/
public class ChoiceDemo extends
Applet
{
Choice os, browser;
String msg = "";
public void init()
{
os = new Choice();
browser = new Choice();
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer 4.0");
browser.add("Internet Explorer 5.0");
browser.add("Internet Explorer 6.0");
browser.add("Lynx 2.4");
browser.select("Netscape 4.x");
add(os);
add(browser);
}
public void paint(Graphics g)
{}}
39
Miss.P.S.Dungarwal
40
Miss.P.S.Dungarwal
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.
41
Miss.P.S.Dungarwal
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.
42
Miss.P.S.Dungarwal
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)
43
Miss.P.S.Dungarwal
44
Miss.P.S.Dungarwal
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.
45
Miss.P.S.Dungarwal
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.
46
Miss.P.S.Dungarwal
METHODS
void setValues(int iValue, int tSize, int min, int max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
47
Miss.P.S.Dungarwal
48
Miss.P.S.Dungarwal
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.
49
Miss.P.S.Dungarwal
TEXTFIELD CONSTRUCTORS
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
50
Miss.P.S.Dungarwal
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( ) 51
Miss.P.S.Dungarwal
52
Miss.P.S.Dungarwal
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
53
Miss.P.S.Dungarwal
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)
54
Miss.P.S.Dungarwal
55
Miss.P.S.Dungarwal
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 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.
56
Miss.P.S.Dungarwal
 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.
57
Miss.P.S.Dungarwal
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
58
Miss.P.S.Dungarwal
FLOWLAYOUT
 FlowLayout is the default layout manager.
 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.
59
Miss.P.S.Dungarwal
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
60
Miss.P.S.Dungarwal
FLOWLAYOUT METHODS
 int getAlignment()
 int getHgap()
 int getVgap()
 int setAlignment(int align)
 int setHgap(int hgap)
 int setVgap(int vgap)
61
Miss.P.S.Dungarwal
public class FlowLayoutDemo extends Applet
{
Checkbox Win98, winNT, solaris, mac;
public void init()
{
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
setLayout(new FlowLayout(FlowLayout.CENTER));
add(Win98); add(winNT);add(solaris);add(mac);
}}
62
Miss.P.S.Dungarwal
63
Miss.P.S.Dungarwal
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.
64
Miss.P.S.Dungarwal
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.
65
Miss.P.S.Dungarwal
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.
66
Miss.P.S.Dungarwal
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."), BorderLayout.NORTH);
add(new Label("The footer message."), BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
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.nn" + " -
George Bernard Shawnn";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
67
Miss.P.S.Dungarwal
68
Miss.P.S.Dungarwal
GRIDLAYOUT
 GridLayout lays out components in a two-
dimensional grid.
 When we instantiate a GridLayout, we define the
number of rows and columns.
69
Miss.P.S.Dungarwal
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. 70
Miss.P.S.Dungarwal
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));
} }}} 71
Miss.P.S.Dungarwal
72
Miss.P.S.Dungarwal
CARDLAYOUT
 The CardLayout class is unique among the other layout
managers in that it stores several different layouts.
 Each layout can be thought of as being on a separate
index card in a deck that can be shuffled so that any card
is on top at a given time.
 This can be useful for user interfaces with optional
components that can be dynamically enabled and disabled
upon user input.
 We can prepare the other layouts and have them hidden,
ready to be activated when needed.
73
Miss.P.S.Dungarwal
 CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
 The first form creates a default card layout.
 The second form allows us to specify the horizontal and
vertical space left between components.
74
Miss.P.S.Dungarwal
METHODS
 void add(Component panelObj, Object name);
 Here name is a string that specifies the name of the
card whose panel is specified by panelObj. After we
have created a deck, our program activates a card by
calling one of the following methods:
 void first(Container deck)
 void last(Container deck)
 void next(Container deck)
 void previous(Container deck)
 void show(Container deck, String cardName)
 deck is a reference to the container (usually a panel)
that holds the cards, and cardName is the name of a
card. 75
Miss.P.S.Dungarwal
76
Miss.P.S.Dungarwal
• // Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample extends Frame impleme
nts ActionListener{
CardLayout card;
Button b1,b2,b3;
CardLayoutExample(){
card=new CardLayout(40,30);
setLayout(card);
77
Miss.P.S.Dungarwal
b1=new Button("Apple");
b2=new Button("Boy");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1,”card1”); add(b2,”card2”); add(b3,”card3”); }
public void actionPerformed(ActionEvent e) {
card.next(this);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
} }
78
Miss.P.S.Dungarwal
79
Miss.P.S.Dungarwal
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.
80
Miss.P.S.Dungarwal
 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.
81
Miss.P.S.Dungarwal
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);
82
Miss.P.S.Dungarwal
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(); } }
83
Miss.P.S.Dungarwal
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.
84
Miss.P.S.Dungarwal
85
Miss.P.S.Dungarwal
 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)
86
Miss.P.S.Dungarwal
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)
87
Miss.P.S.Dungarwal
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( )
88
Miss.P.S.Dungarwal
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2); menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main
(String args[]) {
new MenuExample();
} }
89
Miss.P.S.Dungarwal
90
Miss.P.S.Dungarwal
DIALOGBOX
 Dialog boxes are primarily used to obtain user input.
 They are similar to frame windows, except that dialog
boxes are always child windows of a top-level window.
 Dialog boxes don’t have menu bars.
 In other respects, dialog boxes function like frame windows.
 Dialog boxes may be modal or modeless.
 When a modal dialog box is active, all input is directed to it
until it is closed.
 When a modeless dialog box is active, input focus can be
directed to another window in your program.
91
Miss.P.S.Dungarwal
 Constructors:.
 Dialog(Frame parentWindow, boolean mode)
 Dialog(Frame parentWindow, String title, boolean mode)
 To create Dialog Box:
 Create Frame or Applet
 Create another class which extends Dialog class.
 Call this new class from Frame/Applet class.
 In constructor of Extended Dialog class, use super method
and pass vales to constructor of Dialog
92
Miss.P.S.Dungarwal
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{ public void actionPerformed( ActionEvent e )
{ DialogExample.d.setVisible(false); }
});
d.add( new Label ("Click button to continue."));
d.add(b); d.setSize(300,300);
d.setVisible(true); }
93
Miss.P.S.Dungarwal
FILEDIALOG
 Java provides a built-in dialog box that lets the user
specify a file.
 To create a file dialog box, instantiate an object of type
FileDialog.
 Constructor:
 FileDialog(Frame parent, String boxName)
 FileDialog(Frame parent, String boxName, int how)
 FileDialog(Frame parent)
 Int how: FileDialog.LOAD, FileDialog.SAVE
 Methods:
 String getDirectory( )
 String getFile( )
94
Miss.P.S.Dungarwal
import java.awt.*;
class SampleFrame extends Frame
{
SampleFrame(String title){
super(title); }}
class FileDialogDemo
{public static void main(String args[]){
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);
FileDialog fd = new FileDialog(f, "File Dialog");
fd.setVisible(true);
}}
95
Miss.P.S.Dungarwal
96
Miss.P.S.Dungarwal

More Related Content

What's hot (20)

PDF
Gui
Sardar Alam
 
PPTX
GUI programming
Vineeta Garg
 
PPT
Graphical User Interface (GUI) - 1
PRN USM
 
PDF
The AWT and Swing
adil raja
 
PPT
28 awt
Prachi Vijh
 
PPTX
Complete java swing
jehan1987
 
PPTX
tL19 awt
teach4uin
 
PPT
Java awt
Arati Gadgil
 
PPTX
JAVA AWT
shanmuga rajan
 
PDF
Java awt tutorial javatpoint
Ricardo Garcia
 
PPT
Java Swing JFC
Sunil OS
 
PPTX
Awt
Rakesh Patil
 
PDF
Z blue introduction to gui (39023299)
Narayana Swamy
 
PPT
Swing and AWT in java
Adil Mehmoood
 
PPT
GUI Programming In Java
yht4ever
 
PPT
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
PPTX
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
PPSX
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
PPTX
AWT Packages , Containers and Components
Sohanur63
 
GUI programming
Vineeta Garg
 
Graphical User Interface (GUI) - 1
PRN USM
 
The AWT and Swing
adil raja
 
28 awt
Prachi Vijh
 
Complete java swing
jehan1987
 
tL19 awt
teach4uin
 
Java awt
Arati Gadgil
 
JAVA AWT
shanmuga rajan
 
Java awt tutorial javatpoint
Ricardo Garcia
 
Java Swing JFC
Sunil OS
 
Z blue introduction to gui (39023299)
Narayana Swamy
 
Swing and AWT in java
Adil Mehmoood
 
GUI Programming In Java
yht4ever
 
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
AWT Packages , Containers and Components
Sohanur63
 

Similar to Advance Java Programming (CM5I) 1.AWT (20)

PPT
introduction to JAVA awt programmin .ppt
bgvthm
 
PPT
1.Abstract windowing toolkit.ppt of AJP sub
YugandharaNalavade
 
PPT
fdtrdrtttxxxtrtrctctrttrdredrerrrrrrawt.ppt
havalneha2121
 
PPT
awdrdtfffyfyfyfyfyfyfyfyfyfyfyfyyfyt.ppt
SulbhaBhivsane
 
PPT
Unit 1- awt(Abstract Window Toolkit) .ppt
Deepgaichor1
 
PPTX
Lecture 2 Introduction to AWT (1).ppt.hello
mayurDharmik1
 
PPTX
javaprogramming framework-ppt frame.pptx
DrDGayathriDevi
 
PDF
Abstract Window Toolkit
RutvaThakkar1
 
PDF
Ingles 2do parcial
Harry Ostaiza
 
PPTX
01. introduction to swing
Prashant Mehta
 
PDF
UNIT-2-AJAVA.pdf
PriyanshiPrajapati27
 
PPT
Unit4 AWT, Swings & Layouts power point presentation
SNIGDHAAPPANABHOTLA
 
PPTX
Awt, Swing, Layout managers
swapnac12
 
PPT
Chap1 1.1
Hemo Chella
 
PPT
Chap1 1 1
Hemo Chella
 
DOC
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
PPT
Unit 7 Java
arnold 7490
 
PDF
The java swing_tutorial
sumitjoshi01
 
PDF
The java rogramming swing _tutorial for beinners(java programming language)
Daroko blog(www.professionalbloggertricks.com)
 
introduction to JAVA awt programmin .ppt
bgvthm
 
1.Abstract windowing toolkit.ppt of AJP sub
YugandharaNalavade
 
fdtrdrtttxxxtrtrctctrttrdredrerrrrrrawt.ppt
havalneha2121
 
awdrdtfffyfyfyfyfyfyfyfyfyfyfyfyyfyt.ppt
SulbhaBhivsane
 
Unit 1- awt(Abstract Window Toolkit) .ppt
Deepgaichor1
 
Lecture 2 Introduction to AWT (1).ppt.hello
mayurDharmik1
 
javaprogramming framework-ppt frame.pptx
DrDGayathriDevi
 
Abstract Window Toolkit
RutvaThakkar1
 
Ingles 2do parcial
Harry Ostaiza
 
01. introduction to swing
Prashant Mehta
 
UNIT-2-AJAVA.pdf
PriyanshiPrajapati27
 
Unit4 AWT, Swings & Layouts power point presentation
SNIGDHAAPPANABHOTLA
 
Awt, Swing, Layout managers
swapnac12
 
Chap1 1.1
Hemo Chella
 
Chap1 1 1
Hemo Chella
 
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
Unit 7 Java
arnold 7490
 
The java swing_tutorial
sumitjoshi01
 
The java rogramming swing _tutorial for beinners(java programming language)
Daroko blog(www.professionalbloggertricks.com)
 
Ad

Recently uploaded (20)

PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PPTX
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
PPTX
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
PPTX
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
How to Manage Promotions in Odoo 18 Sales
Celine George
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
How to Manage Promotions in Odoo 18 Sales
Celine George
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
digestive system for Pharm d I year HAP
rekhapositivity
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
Ad

Advance Java Programming (CM5I) 1.AWT

  • 1. Abstract Windowing Toolkit AWT(12 Marks) Miss.P.S.Dungarwal Lecturer in CM Department. SHHJB Polytechnic, Chandwad. 1 Miss.P.S.Dungarwal Advance Java Programming(22517)
  • 2. 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. 2 Miss.P.S.Dungarwal
  • 5. 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. 5 Miss.P.S.Dungarwal
  • 6. 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. 6 Miss.P.S.Dungarwal
  • 7. METHODS OF COMPONENT CLASS Method Description public void add(Component c) inserts a component on this component. public void setSize(int width, int height) sets the size (width and height) of the component. public void setLayout(LayoutManager m) defines the layout manager for the 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, int height) Set the location and size of single component and useful only with null layout. 7 Miss.P.S.Dungarwal
  • 8. 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) • void setLayout(LayoutManager mgr) 8 Miss.P.S.Dungarwal
  • 9. 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. 9 Miss.P.S.Dungarwal
  • 10. AN APPLET IS PANEL IS A CONTAINER java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet 10 Miss.P.S.Dungarwal
  • 11. 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. 11 Miss.P.S.Dungarwal
  • 12. 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 12 Miss.P.S.Dungarwal
  • 14. 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. 14 Miss.P.S.Dungarwal
  • 15. 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) 15 Miss.P.S.Dungarwal
  • 16. 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) 16 Miss.P.S.Dungarwal
  • 17. 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 17 Miss.P.S.Dungarwal
  • 18. PROGRAM USING FRAMES import java.awt.*; class FirstFrame{ 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); } public static void main(String args[]){ FirstFrame f=new FirstFrame(); } } 18 Miss.P.S.Dungarwal
  • 19. PROGRAM USING FRAMES import java.awt.*; class First extends Frame{ First(){ Button b=new Button("click me"); b.setBounds(30,100,80,30); add(b); setSize(300,300); setLayout(null); setVisible(true); } public static void main (String args[]){ First f=new First(); } } 19 Miss.P.S.Dungarwal
  • 20. CONTROLS  Labels  Buttons  Checkbox  CheckboxGroup  Textfield  TextFieldArea  ScollBar 20 Miss.P.S.Dungarwal
  • 21. 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. 21 Miss.P.S.Dungarwal
  • 22. LABELS • Label defines the following constructors: • Label( ) • Label(String str) • Label(String str, int how) • The first version creates a blank label. • The second version creates a label that contains the string specified by str. This string is left-justified. • 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. 22 Miss.P.S.Dungarwal
  • 23. LABEL Methods void setText(String str) String getText( ) void setAlignment(int how) int getAlignment( ) 23 Miss.P.S.Dungarwal
  • 24. CONTROLS // Demonstrate Labels import java.awt.*; import java.applet.*; /* <applet code="LabelDemo" width=300 height=200> </applet> */ public class LabelDemo extends Applet { public void init() { Label one = new Label("One"); Label two = new Label("Two"); Label three = new Label("Three"); // add labels to applet window add(one); add(two); add(three); } } 24 Miss.P.S.Dungarwal
  • 25. 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) 25 Miss.P.S.Dungarwal
  • 26. 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) 26 Miss.P.S.Dungarwal
  • 27. // Demonstrate Buttons import java.awt.*; import java.applet.*; /* <applet code="ButtonDemo" width=250 height=150> </applet> */ public class ButtonDemo extends Applet { String msg = ""; Button yes, no, maybe; public void init() { yes = new Button("Yes"); no = new Button("No"); maybe = new Button(“Understand"); add(yes); add(no); add(maybe); } public void paint(Graphics g) { g.drawString(msg, 6, 100); } } 27 Miss.P.S.Dungarwal
  • 28. 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. 28 Miss.P.S.Dungarwal
  • 29. 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) 29 Miss.P.S.Dungarwal
  • 30. METHODS  boolean getState( )  void setState(boolean on)  String getLabel( )  void setLabel(String str)  void addItemListener(ItemListener l)  void removeItemListener(ItemListener l) 30 Miss.P.S.Dungarwal
  • 31. // Demonstrate check boxes. import java.awt.*; import java.applet.*; /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet { String msg = ""; Checkbox Win98, winNT, solaris, mac; public void init() { Win98 = new Checkbox("Windows 98/XP", null, true); winNT = new Checkbox("Windows NT/2000"); solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); add(Win98); add(winNT); add(solaris); add(mac); } public void paint(Graphics g) {} } 31 Miss.P.S.Dungarwal
  • 33. 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. 33 Miss.P.S.Dungarwal
  • 34. METHODS Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox wh) 34 Miss.P.S.Dungarwal
  • 35. import java.awt.*; import java.applet.*; /* <applet code="CBGroup" width=250 height=200> </applet> */ public class CBGroup extends Applet { String msg = ""; Checkbox Win98, winNT, solaris, mac; CheckboxGroup cbg; public void init() { cbg = new CheckboxGroup(); Win98 = new Checkbox("Windows 98/XP", cbg, true); winNT = new Checkbox("Windows NT/2000", cbg, false); solaris = new Checkbox("Solaris", cbg, false); mac = new Checkbox("MacOS", cbg, false); add(Win98); add(winNT); add(solaris); add(mac);} public void paint(Graphics g) { msg = "Current selection: "; msg += cbg.getSelectedCheckbox().getLabel(); g.drawString(msg, 6, 100); }} 35 Miss.P.S.Dungarwal
  • 37. 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. 37 Miss.P.S.Dungarwal
  • 38. METHODS void add(String name) String getSelectedItem( ) int getSelectedIndex( ) int getItemCount( ) void select(int index) void select(String name) String getItem(int index) 38 Miss.P.S.Dungarwal
  • 39. import java.awt.*; import java.applet.*; /* <applet code="ChoiceDemo" width=300 height=180> </applet> */ public class ChoiceDemo extends Applet { Choice os, browser; String msg = ""; public void init() { os = new Choice(); browser = new Choice(); os.add("Windows 98/XP"); os.add("Windows NT/2000"); os.add("Solaris"); os.add("MacOS"); browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Netscape 5.x"); browser.add("Netscape 6.x"); browser.add("Internet Explorer 4.0"); browser.add("Internet Explorer 5.0"); browser.add("Internet Explorer 6.0"); browser.add("Lynx 2.4"); browser.select("Netscape 4.x"); add(os); add(browser); } public void paint(Graphics g) {}} 39 Miss.P.S.Dungarwal
  • 41. 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. 41 Miss.P.S.Dungarwal
  • 42. 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. 42 Miss.P.S.Dungarwal
  • 43. 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) 43 Miss.P.S.Dungarwal
  • 45. 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. 45 Miss.P.S.Dungarwal
  • 46. 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. 46 Miss.P.S.Dungarwal
  • 47. METHODS void setValues(int iValue, int tSize, int min, int max) int getValue( ) void setValue(int newValue) int getMinimum( ) int getMaximum( ) void setUnitIncrement(int newIncr) void setBlockIncrement(int newIncr) 47 Miss.P.S.Dungarwal
  • 49. 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. 49 Miss.P.S.Dungarwal
  • 50. TEXTFIELD CONSTRUCTORS TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int numChars) 50 Miss.P.S.Dungarwal
  • 51. 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( ) 51 Miss.P.S.Dungarwal
  • 53. 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 53 Miss.P.S.Dungarwal
  • 54. 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) 54 Miss.P.S.Dungarwal
  • 56. 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 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. 56 Miss.P.S.Dungarwal
  • 57.  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. 57 Miss.P.S.Dungarwal
  • 58. 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 58 Miss.P.S.Dungarwal
  • 59. FLOWLAYOUT  FlowLayout is the default layout manager.  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. 59 Miss.P.S.Dungarwal
  • 60. 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 60 Miss.P.S.Dungarwal
  • 61. FLOWLAYOUT METHODS  int getAlignment()  int getHgap()  int getVgap()  int setAlignment(int align)  int setHgap(int hgap)  int setVgap(int vgap) 61 Miss.P.S.Dungarwal
  • 62. public class FlowLayoutDemo extends Applet { Checkbox Win98, winNT, solaris, mac; public void init() { Win98 = new Checkbox("Windows 98/XP", null, true); winNT = new Checkbox("Windows NT/2000"); solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); setLayout(new FlowLayout(FlowLayout.CENTER)); add(Win98); add(winNT);add(solaris);add(mac); }} 62 Miss.P.S.Dungarwal
  • 64. 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. 64 Miss.P.S.Dungarwal
  • 65. 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. 65 Miss.P.S.Dungarwal
  • 66. 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. 66 Miss.P.S.Dungarwal
  • 67. public class BorderLayoutDemo extends Applet { public void init() { setLayout(new BorderLayout()); add(new Button("This is across the top."), BorderLayout.NORTH); add(new Label("The footer message."), BorderLayout.SOUTH); add(new Button("Right"), BorderLayout.EAST); 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.nn" + " - George Bernard Shawnn"; add(new TextArea(msg), BorderLayout.CENTER); } } 67 Miss.P.S.Dungarwal
  • 69. GRIDLAYOUT  GridLayout lays out components in a two- dimensional grid.  When we instantiate a GridLayout, we define the number of rows and columns. 69 Miss.P.S.Dungarwal
  • 70. 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. 70 Miss.P.S.Dungarwal
  • 71. 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)); } }}} 71 Miss.P.S.Dungarwal
  • 73. CARDLAYOUT  The CardLayout class is unique among the other layout managers in that it stores several different layouts.  Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time.  This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input.  We can prepare the other layouts and have them hidden, ready to be activated when needed. 73 Miss.P.S.Dungarwal
  • 74.  CardLayout provides these two constructors: CardLayout( ) CardLayout(int horz, int vert)  The first form creates a default card layout.  The second form allows us to specify the horizontal and vertical space left between components. 74 Miss.P.S.Dungarwal
  • 75. METHODS  void add(Component panelObj, Object name);  Here name is a string that specifies the name of the card whose panel is specified by panelObj. After we have created a deck, our program activates a card by calling one of the following methods:  void first(Container deck)  void last(Container deck)  void next(Container deck)  void previous(Container deck)  void show(Container deck, String cardName)  deck is a reference to the container (usually a panel) that holds the cards, and cardName is the name of a card. 75 Miss.P.S.Dungarwal
  • 77. • // Demonstrate CardLayout. import java.awt.*; import java.awt.event.*; public class CardLayoutExample extends Frame impleme nts ActionListener{ CardLayout card; Button b1,b2,b3; CardLayoutExample(){ card=new CardLayout(40,30); setLayout(card); 77 Miss.P.S.Dungarwal
  • 78. b1=new Button("Apple"); b2=new Button("Boy"); b3=new Button("Cat"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); add(b1,”card1”); add(b2,”card2”); add(b3,”card3”); } public void actionPerformed(ActionEvent e) { card.next(this); } public static void main(String[] args) { CardLayoutExample cl=new CardLayoutExample(); cl.setSize(400,400); cl.setVisible(true); } } 78 Miss.P.S.Dungarwal
  • 80. 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. 80 Miss.P.S.Dungarwal
  • 81.  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. 81 Miss.P.S.Dungarwal
  • 82. 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); 82 Miss.P.S.Dungarwal
  • 83. 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(); } } 83 Miss.P.S.Dungarwal
  • 84. 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. 84 Miss.P.S.Dungarwal
  • 86.  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) 86 Miss.P.S.Dungarwal
  • 87. 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) 87 Miss.P.S.Dungarwal
  • 88. 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( ) 88 Miss.P.S.Dungarwal
  • 89. import java.awt.*; class MenuExample { MenuExample(){ Frame f= new Frame("Menu Example"); MenuBar mb=new MenuBar(); Menu menu=new Menu("Menu"); Menu submenu=new Menu("Sub Menu"); MenuItem i1=new MenuItem("Item 1"); MenuItem i2=new MenuItem("Item 2"); MenuItem i3=new MenuItem("Item 3"); MenuItem i4=new MenuItem("Item 4"); MenuItem i5=new MenuItem("Item 5"); menu.add(i1); menu.add(i2); menu.add(i3); submenu.add(i4); submenu.add(i5); menu.add(submenu); mb.add(menu); f.setMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main (String args[]) { new MenuExample(); } } 89 Miss.P.S.Dungarwal
  • 91. DIALOGBOX  Dialog boxes are primarily used to obtain user input.  They are similar to frame windows, except that dialog boxes are always child windows of a top-level window.  Dialog boxes don’t have menu bars.  In other respects, dialog boxes function like frame windows.  Dialog boxes may be modal or modeless.  When a modal dialog box is active, all input is directed to it until it is closed.  When a modeless dialog box is active, input focus can be directed to another window in your program. 91 Miss.P.S.Dungarwal
  • 92.  Constructors:.  Dialog(Frame parentWindow, boolean mode)  Dialog(Frame parentWindow, String title, boolean mode)  To create Dialog Box:  Create Frame or Applet  Create another class which extends Dialog class.  Call this new class from Frame/Applet class.  In constructor of Extended Dialog class, use super method and pass vales to constructor of Dialog 92 Miss.P.S.Dungarwal
  • 93. import java.awt.*; import java.awt.event.*; public class DialogExample { private static Dialog d; DialogExample() { Frame f= new Frame(); d = new Dialog(f , "Dialog Example", true); d.setLayout( new FlowLayout() ); Button b = new Button ("OK"); b.addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent e ) { DialogExample.d.setVisible(false); } }); d.add( new Label ("Click button to continue.")); d.add(b); d.setSize(300,300); d.setVisible(true); } 93 Miss.P.S.Dungarwal
  • 94. FILEDIALOG  Java provides a built-in dialog box that lets the user specify a file.  To create a file dialog box, instantiate an object of type FileDialog.  Constructor:  FileDialog(Frame parent, String boxName)  FileDialog(Frame parent, String boxName, int how)  FileDialog(Frame parent)  Int how: FileDialog.LOAD, FileDialog.SAVE  Methods:  String getDirectory( )  String getFile( ) 94 Miss.P.S.Dungarwal
  • 95. import java.awt.*; class SampleFrame extends Frame { SampleFrame(String title){ super(title); }} class FileDialogDemo {public static void main(String args[]){ Frame f = new SampleFrame("File Dialog Demo"); f.setVisible(true); f.setSize(100, 100); FileDialog fd = new FileDialog(f, "File Dialog"); fd.setVisible(true); }} 95 Miss.P.S.Dungarwal