3042 - File - JAVA - Notes (Unit 4)
3042 - File - JAVA - Notes (Unit 4)
UNIT – IV
AWT Controls: The AWT Class Hierarchy – User Interface Components – Labels –
Button – Text Components – Check Box – Check Box Group – Choice – List Box – Panels –
Scroll Pane – Menu – Scroll Bar. Working with Frame Class – Colour – Fonts and Layout
Managers. Event Handling: Events – Event Sources – Event Listeners – Event Delegation
Model (EDM) – Handling Mouse and Keyboard Events – Adapter Classes – Inner Classes.
JAVA AWT
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User
Interface (GUI) or Windows-based Java programs
Java AWT components are platform-dependent.
The java.awt package contains AWT API classes
*************************
1. Labels
Example
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);
}
}
******************
2. 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.
Constructors for Button Control
Button defines these two constructors:
Button( )
Button(String str)
Methods for Button Control
String getLabel()
void setLabel(String str)
void setEnabled(Boolean enable)
Void addActionListener(ActionListener l)
void removeActionListener(ActionListener l)
String getActionCommand()
void setActionCommand(String Cmd)
Example
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);
}
}
********************
3. Check Box
Control which allows the user to choose more than one option
Constructors for Check Box Control
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
Methods for Check Box Control
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
void addItemListener(ItemListener l)
void removeItemListener(ItemListener l)
Example
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)
{}
}
*********************
4. Checkbox Group
It is possible to create a set of mutually exclusive check boxes in which one and
only one check box in the group can be checked at any one time.
These check boxes are often called radio button.
Check box groups are objects of type CheckboxGroup.
Only the default constructor is defined, which creates an empty group.
Methods for Checkbox Group Control
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox wh)
Example
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);
}
}
5. Choice Control
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.
Example
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)
{}}
**************************
6. List Control
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.
Constructors for List Control
List( ) - creates a List control that allows only one item to be selected at any one
time
List(int numRows) - the value of numRows specifies the number of entries in
the list that will always be visible
List(int numRows, boolean multipleSelect) - if multipleSelect is true, then the
user may select two or more items at a time
Methods for List Control
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)
***********************
7. Scroll Bar
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.
o slider box (or thumb) for the scroll bar.
The slider box can be dragged by the user to a new position, this action
translates into some form of page up and page down.
Constructors for Scroll Bar
Scrollbar( ) - creates a vertical scroll bar
Scrollbar(int style) - Allow us to specify style Scrollbar.VERTICAL,
Scrollbar.HORIZONTAL
Scrollbar(int style, int iValue, int tSize, int min, int max) - The initial value of
the scroll bar is passed in iValue. The number of units represented by the height
of the thumb is passed in tSize. The minimum and maximum values for the scroll
bar are specified by min and max
Methods for Scroll Bar
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)
**************************
8. Text Component
It is used to get the input from user
There are 2 types of text component
1. Textfield
2. Textarea
1. 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.
Constructors for Textfield Control
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
Methods for Textfield Control
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( )
2. 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)
Methods for Textarea Control
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)
******************************
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
1. Menu( )
2. Menu(String optionName)
3. Menu(String optionName, boolean removable)
Here, optionName specifies the name of the menu selection.
Individual menu items constructors:
1. MenuItem( )
2. MenuItem(String itemName)
3. MenuItem(String itemName, MenuShortcut keyAccel)
Methods
Disable or enable a menu item by using:
1. void setEnabled(boolean enabledFlag)
2. boolean isEnabled( )
Label set and get using:
1. void setLabel(String newName)
2. String getLabel( )
Checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem:
1. CheckboxMenuItem( )
2. CheckboxMenuItem(String itemName)
3. CheckboxMenuItem(String itemName, boolean on)
Status about checkable MenuItem:
1. boolean getState( )
2. void setState(boolean checked)
For add MenuItem:
1. MenuItem add(MenuItem item)
For add MenuBar
1. Menu add(Menu menu)
To get Item from Menu:
1. Object getItem( )
Example
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();
} }
************************
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.
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.
There are following classes that represents the layout managers:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
1. Flow Layout
Example
setLayout(new FlowLayout(FlowLayout.CENTER));
add(Win98); add(winNT);add(solaris);add(mac);
}}
2. Border Layout
Example
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.\n\n" + " -
George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
3. Grid Layout
Example
int k = i * n + j;
if(k > 0)
} }}}
4. Card Layout
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
Methods
Example
import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample extends Frame implements ActionListener{
CardLayout card;
Button b1,b2,b3;
CardLayoutExample(){
card=new CardLayout(40,30);
setLayout(card);
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);
} }
5. GridBag Layout
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.
Example
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(); } }
**************************
Working with Color
Color is encapsulated by the Color class.
Color defines several constants to specify a number of common colors.
We can create our own colors, using one of the Color constructors.
Color( int red, int green, int blue)
Color( int rgbValue)
Color( float red, float green, float blue)
these values must be between 0 and 255.
eg. new Color(255, 100, 100); //light red
Color Methods
Using Hue, Saturation and Brightness
The Hue-Saturation-Brightness(HSB) color model is an alternative to Red-Green
Blue(RGB) for specifying particular colors.
Hue
is a wheel of Color
specified with a number between 0.0 and 1.0
colors approximately red, orange, yellow, green, blue, indigo and violet.
Saturation
scale ranging from 0.0 to 1.0 representing light pastels to intense hues.
Brightness
range from 0.0 to 1.0 where 1 is bright white and 0 is black.
*********************
Working with Fonts
The AWT supports multiple type fonts.
Fonts have a family name, a logical font name and a face name.
family name -> general name of font. Eg. Courier
logical name -> category of font. Eg. Monospaced
face name -> specific font. Eg. Courier Italic
Fonts are encapsulated by the Font class.
Methods (refer book)
The Font class defines these variables
String name – name of the font
float pointSize – size of the font in points
int size – size of the font in points
int style – font style
Determining the Available Fonts
String[ ] getAvailableFontFamilyNames( )
Font[ ] getAllFonts( )
Creating and Selecting a Font
Font constructor
Font(String fontName, int fontStyle, int pointSize)
fontName
name of the desired font
Dialog, DialogInput, SansSerif, Serif and Monospaced supported by all Java
environments
default -> Dialog
fontStyle
style of the font
3 constants (Font.PLAIN, Font.BOLD, Font.ITALIC)
can be ORed together
eg. Font.BOLD | Font.ITALIC
pointSize -> size of the font in points
************************