Unit1 1
Unit1 1
import java.awt.*;
import java.applet.*;
Output:
import java.awt.*;
class Simpleframe extends Frame
{
Simpleframe()
{
setSize(300,300);
setVisible(true);
setTitle("This is Frame window");
setBackground(Color.BLUE);
}
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level. The two most common windows are applet which is
derived from Panel, and second is Frame which is derived from Window.
Component
At the top of the AWT hierarchy is the Component class. 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.
Container
The Container class is a subclass of Component. It has additional methods that
allow other Component objects to be nested within it. A container is responsible for
positioning any components that it contains. It does this through the use of various
layout managers.
Panel
The Panel class is a concrete subclass of Container. Panel is the superclass for Applet.
When screen output is directed to an applet,it is drawn on the surface of a Panel object.
Panel is a window that does not contain a title bar, menu bar, or border. This is why
we don’t see these items when an applet is run inside a browser. When we run an
applet using an applet viewer, the applet viewer provides the title and border.
Other components can be added to a Panel object by its add( ) Once these
components have been added, you can position and resize them manually using the
setLocation( ), setSize( ), setPreferredSize( ), or setBounds( ) methods
defined by Component.
Window
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called Frame
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other
type of window that you will find valuable: Canvas. Canvas encapsulates a blank
window upon which you can draw.
AWT Controls
The AWT supports the following types of controls:
Labels
Button
Checkbox
CheckboxGroup
Choice
Lists
TextField
TextArea
Scroll bars
Sometimes we want to remove a control from a window when the control is no longer
needed. remove( ) method is used to remove the component.To remove all controls
call removeAll( ) method.
Construct:
void remove(Component obj)
Example:
Label l1=new Label(“Information Technology”);
add(l1);
remove(l1);
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.
constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
Example:Using Applet
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);
}
}
Example:Using Frame
import java.awt.*;
We can set or change the text in a label by using the setText( ) method.
To obtain the current label by calling getText( ).
Example:
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);
}
}
We can set the alignment of the string within the label by calling setAlignment( ).
To obtain the current alignment, call getAlignment( ).
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:
Button( )
Button(String str)
The first version creates an empty button.
The second creates a button that contains str as a label.
Example:
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);
}
}
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.
We change the state of a check box by clicking on it.
Constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of the
check box is unchecked.
The second form creates a check box whose label is specified by str. The state of
the check box is unchecked.
The third form allows you to set the initial state of the check box. If on is true, the
check box is initially checked; otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str and
whose group is specified by cbGroup.
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 only one can be selected at any one
time.
To create a set of mutually exclusive check boxes, 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.
Only the default constructor is defined, which creates an empty group.
You can determine which check box in a group is currently selected by calling
getSelectedCheckbox( ).
You can set a check box by calling setSelectedCheckbox( ).
Example:
import java.awt.*;
import java.applet.*;
/* <applet code="checkbox" height=300 width=300></applet> */
Here, name is the name of the item being added. Items are added to the list in the
order in which calls to add( ) occur.
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.
You can set the currently selected item using the select( ) method with either a
zero-based integer index or a string that will match a name in the list.
int getItemCount( )
void select(int index)
void select(String name)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ),
Example
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();
}
}
List
The List class provides a compact, multiple-choice, scrolling selection list. 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:
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. If it is false, then only one item may be selected.
Here, 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. We 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( ).
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
If more than one item is selected, or if no selection has yet been made, null is returned.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. If more
than one item is selected, or if no selection has yet been made, –1 is returned.
For lists that allow multiple selection, you must use either getSelectedItems( ) or
getSelectedIndexes( ), to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected
items.
getSelectedIndexes( ) returns an array containing the indexes of the currently selected
items.
To obtain the number of items in the list, call getItemCount( ).
You can set the currently selected item by using the select( ) method with a
zero-based integer index.
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)
Example
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.
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:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
To obtain the string currently contained in the text field, call getText( ).
To set the text, call setText( ).
String getText( )
void setText(String str)
The user can select a portion of the text in a text field. Also, you can select a portion
of text under program control by using select( ).
We can obtain the currently selected text by calling getSelectedText( ).
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the
characters beginning at startIndex and ending at endIndex–1.
You can control whether the contents of a text field may be modified by the user by
calling setEditable( ).
we can determine editability by calling isEditable( ).
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not.
In setEditable( ), if canEdit is true, the text may be changed. If it is false, the text
cannot be altered.
When you will want the user to enter text that is not displayed, such as a password.
You can disable the echoing of the characters as they are typed by calling
setEchoChar( ).
You can check a text field to see if it is in this mode with the echoCharIsSet( )
method.
You can retrieve the echo character by calling the getEchoChar( ) method.
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)
Example
import java.awt.*;
class Textfield extends Frame
{
Textfield()
{
setSize(300,300);
setVisible(true);
setLayout(null);
setTitle("This is TextField");
setBackground(Color.RED);
Label l1=new Label("Username");
l1.setBounds(30,50,50,50);
TextField t1=new TextField();
t1.setBounds(120,50,100,30);
Label l2 =new Label("Address");
l2.setBounds(30,80,50,50);
TextArea a1=new TextArea();
a1.setBounds(120,100,100,50);
add(l1);
add(t1);
add(l2);
add(a1);
}
public static void main(String args[])
{
Textfield f=new Textfield();
}
}
Example:
import java.awt.*;
class textfieldmethod extends Frame
{
textfieldmethod()
{
setSize(300,300);
setVisible(true);
setLayout(null);
setTitle("This is TextField");
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. Each end has an arrow that you can click to
move the current value of the scroll bar one unit in the direction of the arrow.
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.
Scroll bars are encapsulated by the Scrollbar class.
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
If you construct a scroll bar by using one of the first two constructors, then you need
to set its parameters by using setValues( ), shown here, before it can be used:
To obtain the current value of the scroll bar, call getValue( ). It returns the current
setting. 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( )
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( ).
Example
import java.awt.*;
class ScrollBarExample extends Frame
{
ScrollBarExample()
{
}
}
Layout Managers
A layout manager automatically arranges the controls within a window by using some
type of algorithm. Each Container object has a layout manager associated with it. A
layout manager is an instance of any class that implements the LayoutManager
interface.
The layout manager is set by the setLayout( ) method.
If no call to setLayout( ) is made, then the default layout manager is used.
If we wish to disable the layout manager and position components manually, pass null
for layoutObj.
If you do this, we will need to determine the shape and position of each component
manually, using the setBounds( ) method defined by Component.
The layout manager is notified each time you add a component to a container.
Whenever the
Each component that is being managed by a layout manager contains the
getPreferredSize( ) and getMinimumSize( ) methods. These return the preferred and
minimum size required to display each component.
FlowLayout
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
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
These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
Example
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
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.
Constructors:
BorderLayout( )
BorderLayout(int horz, int vert)
When adding components, use these constants with the following form of
add( ), which is defined by Container:
Here, compObj is the component to be added, and region specifies where the
component will be added.
Example:
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.
Constructors:
by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
import java.awt.*;
import java.applet.*;
/* <applet code="gridlayout" width=250 height=200></applet>*/
public class gridlayout extends Applet
{
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. 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.
You can prepare the other layouts and have them hidden, ready to be activated
when needed.
The cards are typically held in an object of type Panel. This panel must have
CardLayout selected as its layout manager.
The cards that form the deck are also typically objects of type Panel. Thus, you must
create a panel that contains the deck and a panel for each card in the deck. Next, you
add to the appropriate panel the components that form each card. You then add these
panels to the panel for which CardLayout is the layout manager. Finally, you add
this panel to the window.
Once these steps are complete, you must provide some way for the user to select
between cards. One common approach is to include one push button for each card in
the deck.
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:
Here, deck is a reference to the container (usually a panel) that holds the cards, and
cardName is the name of a card.
Calling first( ) causes the first card in the deck to be shown.
To show the last card, call last( ).
To show the next card, call next( ).
To show the previous card, call previous( ).
Both next( ) and previous( ) automatically cycle back to the top or bottom of the deck,
respectively.
The show( ) method displays the card whose name is passed in cardName.
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;
p1.add(winPan, "Windows");
p1.add(otherPan, "Other");
add(p1);
Win.addActionListener(this);
Other.addActionListener(this);
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.
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. Next, create instances of Menu that will define the selections
displayed on the bar.
optionName specifies the name of the menu selection. If removable is true, the
menu can be removed and allowed to float free. Otherwise, it will remain attached to
the menu bar.
Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut
for this item.
Checkable items operate as toggles. Each time one is selected, its state changes. In the
first two forms, the checkable entry is unchecked.
In the third form, if on is true, the checkable entry is initially checked. Otherwise, it is
cleared.
Once you have created a menu item, you must add the item to a Menu object by using
add( ),
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);
menushortcut()
{
setSize(500,500);
setVisible(true);
mb=new MenuBar();
setMenuBar(mb);
m1=new Menu("File");
mb.add(m1);
ms=new MenuShortcut(KeyEvent.VK_X);
i1=new MenuItem("New");
i2=new MenuItem("Open");
i3=new MenuItem("Save as");
i4=new MenuItem("Exit",ms);
m1.add(i1);
m1.add(i2);
m1.add(i3);
m1.addSeparator();
m1.add(i4);
}
public static void main(String args[])
{
menushortcut mc=new menushortcut();
}
}
Dialog Boxes
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.
Constructors
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. The title of the dialog box can be passed in title.
When the dialog box is closed, dispose( ) is called. This method is defined by
Window, and it frees all system resources associated with the dialog box window.
Example:
import java.awt.*;
import java.awt.event.*;
public class DialogEx2 extends WindowAdapter implements ActionListener
{
Frame frame;
Label label1;
Button button1;
Dialog d1;
DialogEx2()
{
frame = new Frame("Frame");
frame.setLayout(new FlowLayout());
frame.setSize(330,250);
frame.setVisible(true);
button1 = new Button("Open Modal Dialog");
label1 = new Label("Click on the button to open a Dialog Box");
frame.add(label1);
frame.add(button1);
button1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==button1)
{
d1= new Dialog(frame,"Modal Dialog",true);
Label label= new Label("You must close this dialog window to use Frame
window",Label.CENTER);
d1.add(label);
d1.addWindowListener(this);
d1.setLocation(new Point(100,100));
d1.setSize(400,200);
d1.setVisible(true);
}
}
public void windowClosing(WindowEvent we)
{
d1.setVisible(false);
}
public static void main(String args[])
{
new DialogEx2();
}
}
FileDialog
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.
Example:
import java.awt.*;
import java.awt.event.*;
f.add(l1);
f.add(p);
f.add(l2);
f.setVisible(true);
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}