UNIT-4 Java Programming
UNIT-4 Java Programming
Unit -4
Abstract Window Toolkit(AWT)
GUI Programming
Introduction
GUI ( Graphical User Interface) , Here the user interact with any application by clicking on
some images or graphics.
Example: if the user wants to print a file, he can click on the printer images and the rest of the
things will be taken care of by the application.
Like magnifying glass symbol for searching, a briefcase symbol for a directory etc.
Hence, the environment where the user can interact with the application through graphics or
images is called GUI (Graphical User Interface)
• TextField,
• Label,
• TextArea,
• RadioButton,
• CheckBox,
• Choice,
• List
• Button
2
Components:
A component represents an object which is displayed pictorially on the screen. For example,
we create an object of Button class as:
Now, b is object of Button class, If we display this b on the screen, it displays a push button.
Therefore, the object b, on going to the screen is becoming a component called ‘PushButton’.
In the same way any component is a graphical representation of an object. Push Buttons, radio
buttons, check boxes etc are all components
3
Container
The Container is a component in AWT that can contain another components like Buttons,
Textfields, labels etc. The classes that extend Container class are known as container such as
Frame, Dialog and Panel.
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.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
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.
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.
import java.awt.Frame;
Output:
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button(“ANURAG UNIVERSITY");
b.setBounds(30,50,180,30);
f.add(b);
5
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Output:
After executing this program we observe that the frame can be minimized, maximized
and resized but cannot be closed. Even if we click on the close button of the frame, it
will not perform any closing action.
Closing a frame means attaching action to the component. To attach action to the frame
we need “EVENT DELIGATION MODEL”
Clicking
Double Clicking
Typing data inside the component
Mouse over etc
When an event is generated on the component, the component will not know about it because
it cannot listen to the event. To let the component understand that an event occurred on it, we
should add some listeners to the components.
6
A listener is an interface which listens to an event coming from a component.
A listener will have some abstract methods which need to be implemented by the
programmer.
When an even is generated by the user on the component, the event is not handled by the
component; on the other hand, the component sends (delegate) the event to the listener
attached to it. The listener will not handle the event. It hands over (Delegates) the event
to an appropriate method. Finally, the method is executed and the event is handled. This
is called ‘Event Delegation Model’
In the delegation event model, listeners must register with the source to receive an event
notification.
Three points to notice here:
1. Events
2. Event Sources
3. Event listeners
Events:
An event is an object that describes a state change in a source.
Some activities that cause events to be generated are:
- pressing a button
- entering a character via keyboard
- clicking mouse
- selecting a checkbox …
7
Event Sources:
A source is an object that generates an event.
Source may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about the event.
Event Listeners:
A listener is an object that is notified when an event occurs.
Every listener has two requirements:
1. It must register with one or more sources.
2. It must implement methods to receive and process events.
Event Classes:
There are many events generated by many sources.
So, we begin with event classes:
At the root of Java event class hierarchy is EventObject class in java.util.
It is the superclass for all events.
It contains two methods:
Object getSource( )
String toString( )
The class AWTEvent in java.awt package is subclass of EventObject and is superclass of all
AWT-based events used by the delegation event model.
Event Classes:
The package java.awt.event defines several types of events generated by various sources.
Event Class Description (Generated when)
MouseEvent Mouse is dragged, moved, clicked, pressed, released, enters or exits a compo
Checkbox Generates item events when the check box is selected or deselected.
Menu Item Generates action events when a menu item is selected; generates item events when
is selected or deselected.
Window Generates window events when a window is activated, closed, deactivated, deicon
or quit.
In addition to these graphical user interface elements, other components, UNIT-IV such as an applet, can
generate events
Event Listener Interfaces:
Listeners are created by implementing one or more of the interfaces defined by the java.awt.event
package. When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument.
Interface
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
WindowListener
ActionListener interface:
void actionPerformed(ActionEvent ae)
ActionEvent class:
String getActionCommand( )
AdjustmentListener interface:
void adjustmentValueChanged(AdjustmentEvent e)
AdjustmentEvent class:
Adjustable getAdjustable( ) int
getAdjustmentType( ) int
getValue( )
int getNewState( )
ItemListener interface:
void itemStateChanged(ItemEvent ie)
ItemEvent class:
Object getItem( )
int getStateChange( )
TextListener interface:
void textValueChanged(TextEvent te)
WindowListener interface:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
WindowEvent class:
Window getWindow( )
Window getOppositeWindow( )
int getOldState( )
11
Adapter Classes:
Adapter classes provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when only some of the events are to be handled by a particular event listener
interface.
}
Adapter Classes:
Program to handle keytyped event
import java.awt.*;
import java.awt.event.*;
public class AdapterKeyDemo extends Frame
12
{
String msg="Hello";
AdapterKeyDemo ()
{
addKeyListener(obj1);
requestFocus();
}
public void paint(Graphics g)
{
g.drawString(msg,50,50);
}
}
class A extends KeyAdapter
{
AdapterKeyDemo akd;
A(AdapterKeyDemo akd1)
{
akd=akd1;
}
public void keyTyped(KeyEvent ke)
{
akd.msg+=ke.getKeyChar();
akd.repaint();
}
public static void main(String arg[])
{
A obj1=new A();
}
}
13
We know frame is also a component. We want to close the frame by clicking on its close button.
Let us follow these steps to see how to use event delegation model to do this.
We should attach a listener to the frame component. Remember, all listeners are available in
java.awt.event package.
The most suitable listener to the frame is ‘window listener’ it can be attached using add
WindowListener() method as;
f.addWindowListener(WindowListener obj);
Note that, the addWindowListerner() method has a parameter that is expecting object of
WindowListener interface. Since it is not possible to create an object to an interface, we should
create an object to the implemented class of the interface and pass it to the method.
Implement all the methods of the WindowListener interface. The following methods are found
in WindowListener interface.
In all the preceding methods, WindowListener interface calls the public void WindowClosing()
method when the frame is being closed. So, implementing this method alone is enough as:
So, when the frame is closed, the body of this method is executed and the application gets
closed. In this way we can handle the frame closing event.
14
Write a program to create a frame and then close it on clicking the close button
import java.awt.*;
import java.awt.event.*;
Output:
In the above program we not only create a frame but also close the frame when the user
clicks on the close button.
In the above example, we had to mention all the methods of WindowListener interface, just
for the sake of one method.
import java.awt.*;
import java.awt.event.*;
Output:
16
An adapter class is an implementation class of a listener interface which contains all methods
implemented with empty body. For example, WindowAdapter is an adapter class of
WindowListener interface.
In the above program, the code of MyClass can be copied directly into addWIndowListener()
method as
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
In this code, we cannot find the name of MyClass anywhere in the code. It means the name of
MyClass is hidden in MyFrame class and hence MyClass is an inner class in MyFrame class
whose name is not mentioned. Such inner class is called ‘anonymous inner class’;
Anonymous inner class is an inner class whose name is not mentioned, and for which only one
object is created.
import java.awt.*;
import java.awt.event.*;
Output:
import java.awt.*;
import java.awt.event.*;
String msg="Hello";
Demo()
{
setVisible(true);
setSize(200,300);
addKeyListener(this);
//requestFocus();
}
public void keyPressed(KeyEvent ke)
{
msg="Pressed";
System.out.println("p");
repaint();
}
public void keyReleased(KeyEvent ke)
{
msg="Released";
System.out.println("r");
repaint();
}
public void keyTyped(KeyEvent ke)
{
msg="Typed";
System.out.println("t");
repaint();
}
public void paint(Graphics g)
{
18
g.drawString(msg,50,50);
}
public static void main(String arg[])
{
new Demo();
}}
Program: Displaying text message in the frame using drawstring() Method
import java.awt.*;
import java.awt.event.*;
}
});
}
Message();
19
m.setSize(400,250); m.setTitle("This is my
Text");m.setVisible(true);
Output:
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
import java.awt.Button;
import java.awt.Frame;
Output
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.
The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to
take someform of input from the user. It inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttonsbut Dialog doesn't have.
Output:
Layout Managers
We Create several components like push buttons, checkboxes, radio buttons etc. in GUI. After
creating these components, they should be placed in the frame (in AWT) or container (in
Swing). While arranging them in the frame or container, they can be arranged in a particular
manner by using layout mangers. We have Layout Manger interface in java.awt package which
is implemented in various classes which provides various layouts to arrange thecomponents.
The following classes represents the layout managers in java
1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBagLayout
To set a particular layout, we should first create an object to the layout class and pass the object
to setLayout() method. For example, to set Flow Layout to the container that holds the
components, we can write:
FlowLayout obj = new FlowLayout();
c.setFlowLayout(obj);
FlowLayout Program:
import java.awt.*;
class FlowLayoutDemo extends Frame
{
FlowLayoutDemo()
{
FlowLayout obj = new FlowLayout(FlowLayout.RIGHT, 10,10);
setLayout(obj);
Button b1,b2,b3,b4;
b1 = new Button("Button1");
b2 = new Button("Button2");
b3 = new Button("Button3");
b4 = new Button("Button4");
add(b1);
add(b2);
add(b3);
add(b4);
}
public static void main (String args[])
{
FlowLayoutDemo demo = new FlowLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Flow Layout");
demo.setVisible(true);
}
}
Output:
Border Layout
import java.awt.*;
class BorderLayoutDemo extends Frame
{
BorderLayoutDemo()
{
BorderLayout obj = new BorderLayout(10,10);
c.setLayout(obj);
Button b1,b2,b3,b4;
b1 = new Button("Button1");
b2 = new Button("Button2");
b3 = new Button("Button3");
b4 = new Button("Button4");
add("North" , b1);
add("East" , b2);
add("South" , b3);
add("Center" , b4);
add(b1, BorderLayout.NORTH);
add(b2, BorderLayout.EAST);
add(b3, BorderLayout.SOUTH);
add(b4,BorderLayout.CENTER);
}
public static void main (String args[])
{
BorderLayoutDemo demo = new BorderLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Flow Layout");
demo.setVisible(true);
}
}
output
Card Layout
import java.awt.*;
import java.awt.event.*;
CardLayoutDemo()
{
card = new CardLayout(50,10);
setLayout(card);
b1 = new Button("Button1");
b2 = new Button("Button2");
b3 = new Button("Button3");
b4 = new Button("Button4");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
card.next(c);
}
import java.awt.*;
class GridLayoutDemo extends Frame
{
GridLayoutDemo()
{
GridLayout grid = new GridLayout(2,3,50,50);
setLayout(grid);
Button b1 = new Button("Button1");
Button b2 = new Button("Button2");
Button b3 = new Button("Button3");J
Button b4 = new Button("Button4");
Button b5 = new Button("Button5");
Button b6 = new Button("Button6");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
}
public static void main (String args[])
{
GridLayoutDemo demo = new GridLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Grid Layout");
demo.setVisible(true);
}
}
Output
GridBag Layout
import java.awt.*;
class GridBagLayoutDemo extends Frame
{
GridBagLayout gbag;
GridBagConstraints cons;
GridBagLayoutDemo()
{
gbag = new GridBagLayout();
setLayout(gbag);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.gridx =0;
cons.gridy =0;
cons.weightx = 0.7;
cons.weighty = 0.7;
gbag.setConstraints(b1,cons);
add(b1);
cons.gridx =1;
cons.gridy =0;
gbag.setConstraints(b2,cons);
add(b2);
cons.gridx =2;
cons.gridy =0;
gbag.setConstraints(b3,cons);
add(b3);
cons.gridx =0;
cons.gridy =1;
cons.ipady = 100;
cons.gridwidth = 3;
gbag.setConstraints(b4,cons);
add(b4);
cons.gridx = 1;
cons.gridy = 2;
cons.ipady = 0;
cons.weighty = 0.8;
cons.anchor = GridBagConstraints.PAGE_END;
cons.insets = new Insets (0,0, 50,0);
cons.gridwidth =2;
gbag.setConstraints(b5,cons);
add(b5);
}
public static void main (String args[])
{
GridBagLayoutDemo demo = new GridBagLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Grid Layout");
demo.setVisible(true);
}
}
Output: