JAVA UNIT-IV Notes
JAVA UNIT-IV Notes
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user interface
components- labels, button, canvas, scrollbars, text components, check box, checkbox groups, choices,
lists panels –scrollpane, dialogs, menubar, graphics, layout manager – layout manager types – border,
grid, flow, card and grid bag.
EVENT HANDLING
In general we can not perform any operation on dummy GUI screen even any button click or select
any item.
To perform some operation on these dummy GUI screen you need some predefined classes and
interfaces.
All these type of classes and interfaces are available in java.awt.event package.
Changing the state of an object is known as an event.
The process of handling the request in GUI screen is known as event handling (event represent an
action). It will be changes component to component.
Note: In event handling mechanism event represent an action class and Listener represent an interface.
Listener interface always contains abstract methods so here you need to write your own logic.
EVENTS
The Events are the objects that define state change in a source.
An event can be generated as a reaction of a user while interacting with GUI elements.
Some of the event generation activities are moving the mouse pointer, clicking on a button, pressing
the keyboard key, selecting an item from the list, and so on.
We can also consider many other user operations as events.
EVENT SOURCES
A source is an object that causes and generates an event.
It generates an event when the internal state of the object is changed.
The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event.
Each event contains its registration method.
Syntax
public void addTypeListener (TypeListener e1)
From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener.
For example, for a keyboard event listener, the method will be called as addKeyListener().
For the mouse event listener, the method will be called as addMouseMotionListener().
When an event is triggered using the respected source, all the events will be notified to registered
listeners and receive the event object.
This process is known as event multicasting.
EVENT LISTENERS
It is also known as event handler.
Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object.
Listener waits until it receives an event.
Once the event is received, the listener process the event and then returns.
EVENT CLASSES AND LISTENER INTERFACES
Event Classes
Description
Listener Interface
ActionEvent
ActionListener
MouseEvent
MouseListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
MouseWheelEvent
MouseWheelListener
WindowEvent
WindowListener
ComponentEvent
ComponentEventListener
ContainerEvent
ContainerListener
AdjustmentEvent
FocusEvent
FocusListener
In this model, a source generates an event and forwards it to one or more listeners.
The listener waits until it receives an event. Once it receives the event, it is processed by the listener
and returns it.
REGISTRATION METHODS
For registering the component with the Listener, many classes provide the registration methods.
Button
public void addActionListener(ActionListener a)
{
}
MenuItem
public void addActionListener(ActionListener a)
{
}
TextField
public void addActionListener(ActionListener a)
{
}
public void addTextListener(TextListener a)
{
}
TextArea
public void addTextListener(TextListener a)
{
}
Checkbox
public void addItemListener(ItemListener a)
{
}
Choice
public void addItemListener(ItemListener a)
{
}
List
public void addActionListener(ActionListener a)
{
}
public void addItemListener(ItemListener a)
{
}
STEPS TO PERFORM EVENT HANDLING
Following steps are required to perform event handling:
Implement the Listener interface and overrides its methods
Register the component with the Listener
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source
and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
The method is now get executed and returns.
Syntax to Handle the Event
class className implements XXXListener
{
.......
.......
}
addcomponentobject.addXXXListener(this);
.......
// override abstract method of given interface and write proper logic
public void methodName(XXXEvent e)
{
.......
.......
}
.......
}
GUI Component
Event class
Listener Interface
Mouse
MouseEvent
MouseListener
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Output:
ADAPTER CLASSES
In a program, when a listener has many abstract methods to override, it becomes complex for the
programmer to override all of them.
For example, for closing a frame, we must override seven abstract methods of WindowListener,
but we need only one method of them.
For reducing complexity, Java provides a class known as "adapters" or adapter class.
Adapters are abstract classes, that are already being overriden.
Adapter class
Listener interface
WindowAdapter
WindowListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter
MouseMotionListener
FocusAdapter
FocusListener
ComponentAdapter
ComponentListener
ContainerAdapter
ContainerListener
HierarchyBoundsAdapter
HierarchyBoundsListener
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
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.
AWT FRAME
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
Frame f=new Frame();
Methods
1. setTitle()
It is used to display user defined message on title bar.
Frame f=new Frame();
f.setTitle("myframe");
2. setBackground()
It is used to set background or image of frame.
Frame f=new Frame();
f.setBackground(Color.red);
3. setForground()
It is used to set the foreground text color.
Frame f=new Frame();
f.setForground(Color.red);
4. setSize()
It is used to set the width and height for frame.
Frame f=new Frame();
f.setSize(400,300);
5. setVisible()
It is used to make the frame as visible to end user.
Frame f=new Frame();
f.setVisible(true);
Note: You can write setVisible(true) or setVisible(false), if it is true then it visible otherwise not visible.
7.add()
It is used to add non-container components (Button, List) to the frame.
Frame f=new Frame();
Button b=new Button("Click");
f.add(b);
Explanation: In above code we add button on frame using f.add(b), here b is the object of Button class..
Example
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
f.setForeground(Color.red);
f.setLayout(new FlowLayout());
Button b1=new Button("Submit");
Button b2=new Button("Cancel");
f.add(b1);f.add(b2);
f.setSize(500,300);
f.setVisible(true);
}
}
Output
AWT PANEL
It is a predefined class used to provide a logical container to hold various GUI component. Panel always
should exist as a part of frame.
Note: Frame is always visible to end user where as panel is not visible to end user.
Panel is a derived class of container class so you can use all the methods which is used in frame.
Syntax
Panel p=new Panel();
Example
import java.awt.*;
class PanelFrame
{
PanelFrame()
{
Frame f=new Frame();
f.setSize(600,400);
f.setBackground(Color.pink);
f.setLayout(new BorderLayout());
Panel p1=new Panel();
p1.setBackground(Color.cyan);
Label l1 =new Label("Enter Uname");
TextField tf1=new TextField(15);
Label l2=new Label("Enter Passward");
TextField tf2=new TextField(15);
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
f.add("North",p1);
Panel p2=new Panel();
p2.setBackground(Color.yellow);
Button b1=new Button("Send");
Button b2=new Button("Clear");
p2.add(b1);
p2.add(b2);
f.add("South",p2);
f.setVisible(true);}
public static void main(String[] args)
{
PanelFrame pf=new PanelFrame();
}
}
Output:
AWT Label
The object of the Label class is a component for placing text in a container. It is used to display a single
line of read only text. The text can be changed by a programmer but a user cannot edit it directly.
Example
import java.awt.*;
public class LabelExample
{
public static void main(String args[])
{
Frame f = new Frame ("Label example");
Label l1, l2;
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
Java AWT Button
A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed.
Example
import java.awt.*;
public class ButtonExample
{
public static void main (String[] args)
{
Frame f = new Frame("Button Example");
Button b = new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}
}
Output:
FLOWLAYOUT
This layout is used to arrange the GUI components in a sequential flow (that means one after another
in horizontal way)
You can also set flow layout of components like flow from left, flow from right.
FlowLayout Left
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
FlowLayout Right
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.RIGHT))
EXAMPLE
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
MyFlowLayout()
{
JFrame f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output:
GRIDLAYOUT
This layout is used to arrange the GUI components in the table format.
EXAMPLE
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
MyGridLayout()
{
JFrame f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
Output
CARDLAYOUT
The CardLayout class manages the components in such a manner that only one component is visible at
a time. It treats each component as a card that is why it is known as CardLayout.
Commonly used methods of CardLayout class
1. public void next(Container parent): is used to flip to the next card of the given container.
2. public void previous(Container parent): is used to flip to the previous card of the given container.
3. public void first(Container parent): is used to flip to the first card of the given container.
4. public void last(Container parent): is used to flip to the last card of the given container.
5. public void show(Container parent, String name): is used to flip to the specified card with the given
name.
EXAMPLE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener
{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
{
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args)
{
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells.
Each component occupies one or more cells known as its display area. Each component associates
an instance of GridBagConstraints.
With the help of constraints object we arrange component's display area on the grid.
The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;