0% found this document useful (0 votes)
36 views69 pages

Chapter 1

The document discusses various Java GUI components from the Abstract Window Toolkit (AWT). It describes the class hierarchy with Component at the top, and subclasses like Container, Window, Panel, and Frame. It then explains common components like Label, Button, Checkbox, Choice, and List - describing their constructors, methods to set/get properties, and examples of how to use them in applets and frames.

Uploaded by

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

Chapter 1

The document discusses various Java GUI components from the Abstract Window Toolkit (AWT). It describes the class hierarchy with Component at the top, and subclasses like Container, Window, Panel, and Frame. It then explains common components like Label, Button, Checkbox, Choice, and List - describing their constructors, methods to set/get properties, and examples of how to use them in applets and frames.

Uploaded by

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

Advanced Java Programming

Archana Gopnarayan
Lecturer , Department of Information Technology (NBA Accrediated)
Vidyalankar Polytechnic
AWT (Abstract Window Toolkit)

import java.awt.*;

Component

Container

Window Panel

Frame Applet

Fig:The class hierarchy for Panel and Frame


Component
• Component is an abstract class that encapsulates all of the
attributes of a visual component.
• All user interface elements that are displayed on the screen
and that interact with the user are subclasses of Component.
• A Component object is responsible for remembering the
current foreground and background colors and the currently
selected text font.
• Some common subclasses of Component are Button,
Checkbox, Label, Scrollbar, TextField, and TextArea
Container

• The Container class is a subclass of Component.


• For a component to be placed on the screen, it must be placed
within a Container.
• A container is responsible for laying out (that is, positioning)
any components that it contains.
• The job of a Container is to hold and display Components.
• A Container is also a Component.
To create an applet
• class MyApplet extends Applet { … }
– this is the only way to make an Applet
• You can add components to the applet
• It’s best to add components in init( )
Some types of components
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 defines the following constructors:
Label( )
Label(String str)
Label(String str, int how)
Label
• 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.
Label
• We can set or change the text in a label by using the method
setText( ) .
• Obtain the current label by calling getText( ).

Construct:
void setText(String str)
String getText( )
Label
• We can set the alignment of the string within the label by
calling setAlignment( ).
• To obtain the current alignment, method is getAlignment( ).

Construct:
void setAlignment(int how)
int getAlignment( )
Label
import java.awt.*;
import java.applet.*;
/* <applet code="LabelDemo" width=300 height=200> </applet> */
public class LabelDemo extends Applet {
public void init() {
Label l1 = new Label("One");
Label l2 = new Label("Two");
Label l3 = new Label("Three");
// add labels to applet window
add(l1);
add(l2);
add(l3);
}
}
Label
import java.awt.*;
import java.applet.*;
/* <applet code="LabelDemo" width=300 height=200> </applet> */

public class LabelDemo extends Applet


{
public void init()
{
Label a = new Label("Information Technology");
Label b =new Label();
String s=a.getText();
b.setText(s);
add(l1);
add(l2);
}
}
Label
import java.awt.*;
class Labelframe extends Frame
{
Labelframe()
{
setSize(300,300);
setVisible(true);

Label l1=new Label("Name",Label.LEFT);


l1.setBounds(30,30,80,30);
add(l1);
}
public static void main(String args[])
{
Labelframe f=new Labelframe();
}
}
Button
• A push button is a component that contains a label and that
generates an event when it is pressed.

Constructor:
Button( )
Button(String str)
Button
• We can set its label by calling setLabel( ).
• We can retrieve its label by calling getLabel( ).

These methods are as follows:


void setLabel(String str)
String getLabel( )
Button
import java.awt.*;
import java.applet.*;
/* <applet code=“buttonDemo" width=300 height=200> </applet> */
public class buttonDemo extends Applet {
public void init() {
Button b1 = new Button("One");
Button b2 = new Button(“Two");
add(b1);
add(b2);
}
}
Button
import java.awt.*;
public class ButtonExample extends Frame
{
ButtonExample()
{
setSize(400,400);
setLayout(null);
setVisible(true);
setBackground(Color.YELLOW);
Button b1 = new Button("Submit");
b1.setBounds(30,50,50,30);
Button b2 = new Button("cancel");
b2.setBounds(150,50,50,30);
add(b1);
add(b2);
}
public static void main(String args[])
{
ButtonExample e=new ButtonExample();
}
}
Checkbox
• 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.
• Check boxes can be used individually or as part of a group.
Check boxes are objects of the Checkbox class.
Checkbox

Checkbox supports these constructors:

Checkbox( )

Ex Checkbox c1=new Checkbox();

Checkbox(String str)

Checkbox c1=new Checkbox(“Information Technology”);

Checkbox(String str, boolean on)

Checkbox c1=new Checkbox(“Information Technology”,true);


Checkbox
• To retrieve the current state of a check box, call getState( ).
• To set its state, call setState( ).
• We can obtain the current label associated with a check box by calling
getLabel( ).
• To set the label, call setLabel( ).

These methods are as follows:

void setState(boolean on)

boolean getState( )

void setLabel(String str)

String getLabel( )
CheckboxGroup
• 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 buttons.
• To create a set of mutually exclusive check boxes, you must
first define the group to which they will belong and then
specify that group when you construct the check boxes.
• Check box groups are objects of type CheckboxGroup.
CheckboxGroup
• You can determine which check box in a group is currently
selected by calling getSelectedCheckbox( ).
• You can set a check box by calling setSelectedCheckbox( ).

Checkbox getSelectedCheckbox( )

void setSelectedCheckbox(Checkbox which)


Example
import java.awt.*;
import java.applet.*;
/* <applet code="checkbox" height=300 width=300></applet> */
public class checkbox extends Applet
{
public void init()
{
Checkbox c1= new Checkbox("IF");
Checkbox c2= new Checkbox("CO");
CheckboxGroup g1= new CheckboxGroup();
Checkbox c3= new Checkbox("Male",g1,true);
Checkbox c4= new Checkbox("Female",g1,false);
add(c1);
add(c2);
add(c3);
add(c4);
}
Example
import java.awt.*;
public class Checkboxdemo extends Frame
{
Checkboxdemo()
{
setSize(400,400);
setLayout(null);
setVisible(true);
Checkbox c1= new Checkbox("IF");
c1.setBounds(50,50, 75,75);
Checkbox c2= new Checkbox("CO");
c2.setBounds(50,100, 75,75);
CheckboxGroup g1= new CheckboxGroup();
Checkbox c3= new Checkbox("Male",g1,true);
c3.setBounds(50,150, 75,75);
Checkbox c4= new Checkbox("Female",g1,false);
c4.setBounds(140,150, 75,75);
add(c1);
add(c2);
add(c3);
add(c4);
}
public static void main(String args[])
{
Checkboxdemo e=new Checkboxdemo();
}
}
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.
• takes up only enough space to show the currently selected item. When the
user clicks on it, the whole list of choices pops up, and a new selection can
be made.
• 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.

Choice only defines the default constructor, which creates an empty list.
Choice()
• To add a selection to the list, call add( ).

add(String name)
Choice Controls
• To determine which item is currently selected ,getSelectedItem( ) or
getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )
• The getSelectedItem( ) method returns a string containing the name of the
item.
• getSelectedIndex( ) returns the index of the item.
• The first item is at index 0. By default, the first item added to the list is
selected.
• To obtain the number of items in the list, call getItemCount( ).
• We can set the currently selected item using the select( ) method .
Choice Controls
int getItemCount( )
void select(int index)
void select(String name)

getItem( ), to obtain the name associated with item

String getItem(int index)


Choice Controls
import java.awt.*;
public class ChoiceExample extends Frame
{
ChoiceExample()
{
setSize(400,400);
setLayout(null);
setVisible(true);
Choice c1=new Choice();
c1.setBounds(100,100, 75,75);
c1.add("Item 1");
c1.add("Item 2");
c1.add("Item 3");
c1.add("Item 4");
c1.add("Item 5");
add(c1);
}
public static void main(String args[])
{
ChoiceExample e=new ChoiceExample();
}
}
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 provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
Lists
• To add a selection to the list, call add( ).
It has the following two forms:
void add(String name)
void add(String name, int index)
• name is the name of the item added to the list. The first form adds
items to the end of the list.
• The second form adds the item at the index specified by index.
• Indexing begins at zero. You can specify –1 to add the item to the end
of the list.
• For lists that allow only single selection, you can determine which
item is currently selected by calling either getSelectedItem( ) or
getSelectedIndex( ).
These methods are
String getSelectedItem( )
int getSelectedIndex( )
List
For lists that allow multiple selection, you must use either getSelectedItems( )
or getSelectedIndexes( )

String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )

•To obtain the number of items in the list, call getItemCount( ).


•To set the currently selected item by using the select( ) method
These methods are shown here:
int getItemCount( )
void select(int index)
•Given an index, you can obtain the name associated with the item at that
index by calling getItem( )
String getItem(int index)
List
import java.awt.*;
public class ListExample extends Frame
{
ListExample()
{
setSize(400,400);
setLayout(null);
setVisible(true);
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
add(l1);
}
public static void main(String args[])
{
ListExample e=new ListExample();
}
}
TextField
• The TextField class implements a single-line text-entry area,
usually called an edit control.
• TextField is a subclass of TextComponent
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
TextField
• To obtain the string currently contained in the text field, call
getText( ).
• To set the text, setText( ).

String getText( )
void setText(String str)

• The user can select a portion of the text in a text field


by using select( ).
void select(int startIndex, int endIndex)
• program can obtain the currently selected text by calling
getSelectedText( ).
String getSelectedText( )

• You can control whether the contents of a text field may be


modified by the user by calling setEditable( ).
void setEditable(boolean canEdit)

• You can determine editability by calling isEditable( ).

boolean isEditable( )
• We can disable the echoing of the characters as they are typed
by calling setEchoChar( ).

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.
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)
TextArea
Constant values for Bars:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Scrollbar
• Scroll bars are used to select continuous values between a specified
minimum and maximum.
• The current value of the scroll bar relative to its minimum and maximum
values is indicated by the slider box (or thumb) for the scroll bar.
Scrollbar
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

The first form creates a vertical scroll bar.


The second and third forms allow you to specify the orientation of the scroll bar.
If style is Scrollbar.VERTICAL, a vertical scroll bar is created.
If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.

If you construct a scroll bar by using one of the first two constructors, then you need
to set its parameters by using setValues( )

void setValues(int initialValue, int thumbSize, int min, int max)


Scrollbar
• To obtain the current value of the scroll bar, call getValue( ).
• To set the current value, call setValue( ).

int getValue( )
void setValue(int newValue)

• We can also retrieve the minimum and maximum values via


getMinimum( ) and getMaximum( )

int getMinimum( )
int getMaximum( )
Scrollbar
• By default, 1 is the increment added to or subtracted from the scroll bar
each time it is scrolled up or down one line.
• You can change this increment by calling setUnitIncrement( ).
• By default, page-up and page-down increments are 10. You can change this
value by calling setBlockIncrement( ).

void setUnitIncrement(int newIncr)


void setBlockIncrement(int newIncr)
Scrollbar
import java.awt.*;
class ScrollBarExample extends Frame
{
ScrollBarExample()
{
setTitle("Scrollbar in Java Example");
setSize(520,200);
setVisible(true);
setLayout(new FlowLayout());
Label lblHor =new Label("Horizontal Scrollbar");
Scrollbar sl = new Scrollbar(Scrollbar.HORIZONTAL,50,10,0,100);
Label lblver =new Label("Vertical Scrollbar");
Scrollbar s2 = new Scrollbar(Scrollbar.VERTICAL,10,5,0,10);
add(lblHor);
add(sl);
add(lblver);
add(s2);
}
Scrollbar
public static void main(String args[])
{
ScrollBarExample frame = new ScrollBarExample();

}
}
Arranging components
• Every Container has a layout manager
• The default layout for a Panel is FlowLayout
• The default layout for a Applet is FlowLayout
• You could set it explicitly with
setLayout (new FlowLayout( ));
FlowLayout
• FlowLayout is the default layout .
• Components are laid out from the upper-left corner, left to right and top
to bottom.
constructors for FlowLayout:
FlowLayout( )
Ex: setLayout(new FlowLayout());
or
FlowLayout f=new FlowLayout();
setLayout(f);

FlowLayout(int how)
Ex: setLayout(new FlowLayout(FlowLayout.LEFT));

FlowLayout(int how, int horz, int vert)


Ex: setLayout(new FlowLayout(FlowLayout.RIGHT,20,20));
FlowLayout
• The first form creates the default layout, which centers components and
leaves five pixels of space between each component.
• The second form lets you specify how each line is aligned. Valid values
for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING

• The third form allows you to specify the horizontal and vertical space
left between components in horz and vert, respectively.
FlowLayout
import java.awt.*;
import java.applet.*;
/* <applet code="FlowLayoutDemo" width=250 height=200></applet>*/
public class FlowLayoutDemo extends Applet
{
Checkbox Win98, winNT, solaris, mac;
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));
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);
}
BorderLayout

• At most five components


can be added
• If you want more
components, add a Panel,
then add components to it.
• setLayout (new
BorderLayout());

add (BorderLayout.NORTH, new Button(“NORTH”));


BorderLayout
• The four sides are referred to as north, south, east, and west. The middle
area is called the center.
Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
• The first form creates a default border layout.
• The second allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.

• BorderLayout defines the following constants that specify the regions:


BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout with five Buttons
import java.awt.*;
import java.applet.*;
/* <applet code="BorderLayoutDemo" width=250 height=200></applet>*/
public class BorderLayoutDemo extends Applet
{
Button win98, winNT, solaris, mac ,win10;
public void init()
{
setLayout(new BorderLayout());
win98=new Button("Windows 98");
winNT=new Button("Windows NT");
solaris=new Button("Solaris");
mac=new Button("Mac");
win10=new Button("Windows 10");

add(win98,BorderLayout.EAST);
add(winNT,BorderLayout.WEST);
add(solaris,BorderLayout.NORTH);
add(mac,BorderLayout.SOUTH);
add(win10,BorderLayout.CENTER);
}
GridLayout
• GridLayout lays out components in a two-dimensional grid. When you
instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
Example
import java.awt.*;
import java.applet.*;
/* <applet code="gridlayout" width=250 height=200></applet>*/
public class gridlayout extends Applet
{

public void init()


{
setLayout(new GridLayout(3,3));
for(int i=1;i<=9;i++)
{
add(new Button("Button"+i));
}
}
}
CardLayout
• The CardLayout class is unique among the other layout managers in that it
stores several different layouts.
• This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input.

The constructors supported by CardLayout are shown here:


CardLayout( )
CardLayout(int horz, int vert)
CardLayout
When card panels are added to a panel, they are usually given a name. Thus,
most of the time, you will use this form of add( ) when adding cards to a
panel:

void add(Component panelObj, Object name)

After you have created a deck, your program activates a card by calling one of
the following methods defined by CardLayout:

void first(Container deck)


void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
CardLayout Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="CardLayoutDemo" width=300 height=100></applet>*/
public class CardLayoutDemo extends Applet implements ActionListener
{
Checkbox winXP, winVista, solaris, mac;
Button Win, Other;
Panel p1;
CardLayout cardLO;
public void init()
{
Win = new Button("WINDOWS PANEL");
Other = new Button("OTHER PANEL");
add(Win);
add(Other);
CardLayout Example
cardLO = new CardLayout();
p1 = new Panel();
p1.setLayout(cardLO);

winXP = new Checkbox("Windows XP",true);


winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

Panel winPan = new Panel();


winPan.add(winXP);
winPan.add(winVista);

Panel otherPan = new Panel();


otherPan.add(solaris);
otherPan.add(mac);
CardLayout Example
p1.add(winPan, "Windows");
p1.add(otherPan, "Other");
add(p1);

Win.addActionListener(this);
Other.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource() == Win)
{
cardLO.show(p1, "Windows");
}
CardLayout Example
else
{
cardLO.show(p1, "Other");
}
}
}
Menu Bars and Menus
• A top-level window can have a menu bar associated with it. A menu
bar displays a list of top-level menu choices. Each choice is associated
with a drop-down menu item.
• This concept is implemented by using the classes: MenuBar, Menu,
and MenuItem.
• It is also possible to include checkable menu items. These are menu
options of type CheckboxMenuItem and will have a check mark next
to them when they are selected.
• To create a menu bar, first create an instance of MenuBar. This class only
defines the default constructor.
MenuBar()
• Next, create instances of Menu that will define the selections displayed
on the bar.
Following are the constructors for Menu:
Menu( )
Ex: Menu m1=new Menu();
Menu(String optionName)
Ex: Menu m1=new Menu("COLOR");
Menu(String optionName, boolean removable)
Ex: Menu m1=new Menu("COLOR",true);
Individual menu items are of type MenuItem.

MenuItem( )
MenuItem i1=new MenuItem();
MenuItem(String itemName)
MenuItem i1=new MenuItem("BLUE");
MenuItem(String itemName, MenuShortcut keyAccel)
CheckboxMenuItem( )
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName, boolean on)
setEnabled(): Disabled or enabled the item
void setEnabled(boolean value)
isEnabled(): Determine the status
Boolean isEnabled()
setLabel()
void setLabel(String name)
getLabel()
String getLabel()
setState()
void setState(Boolean checked)
getState()
Boolean getState()
Example
import java.awt.*;
public class menucolour extends Frame
{
menucolour()
{
setSize(500,500);
setVisible(true);
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu m1=new Menu("COLOR");
mb.add(m1);
MenuItem i1=new MenuItem("BLUE");
MenuItem i2=new MenuItem("RED");
MenuItem i3=new MenuItem("BLACK");
m1.add(i1);
m1.add(i2);
m1.add(i3);
Menu m2=new Menu("FONT");
mb.add(m2);
MenuItem f1=new MenuItem("12");
MenuItem f2=new MenuItem("14");
MenuItem f3=new MenuItem("16");
m2.add(f1);
m2.add(f2);
m2.add(f3);
}
public static void main(String args[])
{
menucolour mc=new menucolour();
}
}
Dialog Box
• Dialog boxes are primarily used to obtain user input and are often child
windows of a top-level window.
• Dialog boxes don’t have menu bars, but in other respects, they 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. This means that you cannot access other parts of your program until
you have closed the dialog box.
• When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program remain
active and accessible.
•Two commonly used constructors are shown here:
– Dialog(Frame parentWindow, boolean mode)
– Dialog(Frame parentWindow, String title, boolean mode)
•Here, parentWindow is the owner of the dialog box. If mode is true, the dialog
box is modal. Otherwise, it is modeless.
File Dialog
File dialog box is the standard file dialog box provided by the operating
system.

FileDialog constructors:
FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)

Here, parent is the owner of the dialog box. The boxName parameter
specifies the name displayed in the box’s title bar. If boxName is omitted,
the title of the dialog box is empty.
If how is FileDialog.LOAD, then the box is selecting a file for reading. If
how is FileDialog.SAVE, the box is selecting a file for writing.
If how is omitted, the box is selecting a file for reading.

You might also like