Java Unit-4
Java Unit-4
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
Events
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion,
etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
An event handler is a function or method that executes program statements in response to
an event. A software program that processes activities such as keystrokes and mouse
movements is what an event handler is. Event handlers in Web sites make Web content
dynamic.
The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. Its concept is quite simple: a source generates an event and sends
it to one or more listeners.
In this scheme, the listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns. The advantage of this design is
that the application logic that processes events is cleanly separated from the user interface
logic that generates those events.
A user interface element is able to ―delegate‖ the processing of an event to a
separate piece of code. In the delegation event model, listeners must register with a
source in order to receive an event notification. This provides an important benefit:
notifications are sent only to listeners that want to receive them.
Event Source:
• Events are generated from the source(components). There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
• An object on which an event occurs is referred to as a source. The source is in
charge of informing the handler about the event that occurred. There are various
sources like buttons, checkboxes, lists, menu-item, choices, scrollbars, text
components, windows, etc.
Event Listeners:
• Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
• When an event occurs, an object named an event listener is called. The listeners
need two things: first, they must be registered with a source; however, they can
be registered with multiple sources to receive event notifications.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
ActionListener • actionPerformed()
AdjustmentListener • adjustmentValueChanged()
• componentResized()
• componentShown()
ComponentListener
• componentMoved()
• componentHidden()
• componentAdded()
ContainerListener
• componentRemoved()
• focusGained()
FocusListener
• focusLost()
ItemListener • itemStateChanged()
• keyTyped()
KeyListener • keyPressed()
• keyReleased()
Listener Interface Methods
• mousePressed()
• mouseClicked()
MouseListener • mouseEntered()
• mouseExited()
• mouseReleased()
• mouseMoved()
MouseMotionListener
• mouseDragged()
MouseWheelListener • mouseWheelMoved()
TextListener • textChanged()
• windowActivated()
• windowDeactivated()
• windowOpened()
WindowListener • windowClosed()
• windowClosing()
• windowIconified()
• windowDeiconified()
Example 1:
// Java program to demonstrate the
// event handling within the class
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
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.
Output:
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has
three methods.
3. public abstract void keyTyped (KeyEvent It is invoked when a key has been
e); typed.
Methods inherited
java.awt.EventListener
In the following example, we are implementing the methods of the KeyListener interface.
KeyListenerExample.java
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces. So it saves code.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
In the following example, we are implementing the WindowAdapter class of AWT and one
its methods windowClosing() to close the frame window.
AdapterExample.java
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.
Java AWT calls the native platform calls the native platform (operating systems) subroutine
for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix. The
reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
AWT Hierarchy
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.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.
Types of containers:
1. Window
2. Panel
3. Frame
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. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
public void setSize(int width,int Sets the size (width and height) of the component.
height)
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
public void setVisible(boolean status) Changes the visibility of the component, by default
false.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
AWTExample1.java
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.
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.
It is called a passive control as it does not create any event when it is accessed. To create a
label, we need to create the object of Label class.
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
2. Label(String text) It constructs a label with the given string (left justified
by default).
3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.
1. void setText(String text) It sets the texts for label with the specified text.
2. void setAlignment(int alignment) It sets the alignment for label with the specified
alignment.
7. protected String paramString() It returns the string the state of the label.
In the following example, we are creating two labels l1 and l2 using the Label(String text)
constructor and adding them into the frame.
LabelExample.java
1. import java.awt.*;
2. public class LabelExample {
3. public static void main(String args[]){
4. // creating the object of Frame class and Label class
5. Frame f = new Frame ("Label example");
6. Label l1, l2;
7. // initializing the labels
8. l1 = new Label ("First Label.");
9. l2 = new Label ("Second Label.");
10. // set the location of label
11. l1.setBounds(50, 100, 100, 30);
12. l2.setBounds(50, 150, 100, 30);
13. // adding labels to the frame
14. f.add(l1);
15. f.add(l2);
16. // setting size, layout and visibility of frame
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }
Output:
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.
When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives the
all the events, then it passes an action event by calling its own method processActionEvent.
This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.
2. Button (String It constructs a new button with given string as its label.
text)
1. void setText (String text) It sets the string message on the button
3. void setLabel (String label) It sets the label of button with the specified string.
11. protected String paramString() It returns the string which represents the state of
button.
15. void setActionCommand(String It sets the command name for the action event
command) given by the button.
Note: The Button class inherits methods from java.awt.Component and java.lang.Object
classes.
Java AWT Button Example
ButtonExample.java
1. import java.awt.*;
2. public class ButtonExample {
3. public static void main (String[] args) {
4. // create instance of frame with the label
5. Frame f = new Frame("Button Example");
6. // create instance of button with label
7. Button b = new Button("Click Here");
8. // set the position for the button in frame
9. b.setBounds(50,100,80,30);
10. // add button to the frame
11. f.add(b);
12. // set size, layout and visibility of frame
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.
Class methods
Sr. Method name Description
no.
In the following example, we are creating a Canvas in the Frame and painting a red colored
oval inside it.
CanvasExample.java
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.
3 Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, orientation, initial value, visible amount, and
int maximum) minimum and maximum values.
Where the parameters,
In the following example, we are creating a scrollbar using the Scrollbar() and adding it into
the Frame.
ScrollbarExample1.java
The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the event
is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also
be done using ActionEvent; if the ActionEvent is enabled on the text field, then the
ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
2. TextField(String text) It constructs a new text field initialized with the given
string text to be displayed.
4. TextField(String text, It constructs a new text field with the given text and given
int columns) number of columns (width).
TextFieldExample1.java
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
3. Checkbox(String label, boolean It constructs a checkbox with the given label and
state) sets the given state.
4. Checkbox(String label, boolean It constructs a checkbox with the given label, set
state, CheckboxGroup group) the given state in the specified checkbox group.
CheckboxExample1.java
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
In the following example, we are creating a choice menu using Choice() constructor. Then we
add 5 items to the menu using add() method and Then add the choice menu into the Frame.
ChoiceExample1.java
Output:
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
Graphics in Applet
The Graphics class, located within the java.awt package, is an abstract superclass that
provides a unified interface for drawing shapes, text, and images onto the screen. It
encapsulates the basic drawing operations that every device must support, enabling Java
applications to render 2D graphics in a platform-independent manner.
The Graphics class provides a suite of methods for drawing shapes, filling shapes, managing
color and font settings, and more. Here are some of its most important methods :−
• public abstract void drawString(String str, int x, int y) − This method is used to
draw a specified string at the specified location (x, y).
• public void drawRect(int x, int y, int width, int height) − This method draws a
rectangle from the point (x, y) with the specified width and height
• public abstract void fillRect(int x, int y, int width, int height) − This method is
used to fill a rectangle from the point (x, y) with the specified width and height.
• public abstract void setColor(Color c) − This method sets the graphics current color
to the specified color.
• public abstract void setFont(Font font) − This method sets the graphics context's
current font to the specified font.
• public abstract void drawOval(int x, int y, int width, int height) − This method
draws an oval bounded by the specified rectangle from the point (x, y) with the
specified width and height.
• public abstract void fillOval(int x, int y, int width, int height) − This method fills
an oval bounded by the specified rectangle from the point (x, y) with the specified
width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2) − This method draws a
line between points (x1, y1) and (x2, y2)
Example program:
import java.awt.*;
import java.awt.event.*;
Output:
BorderLayout (LayoutManagers)
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
frame or window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
FileName: Border.java
1. import java.awt.*;
2. import javax.swing.*;
3. public class Border
4. {
5. JFrame f;
6. Border()
7. {
8. f = new JFrame();
9. // creating buttons
10. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
11. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
12. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
13. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
14. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
15. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
16. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
17. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
18. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
19. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
20. f.setSize(300, 300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new Border();
25. }
26. }
Output:
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.
FileName: MyGridLayout.java
1. import java.awt.*;
2. import javax.swing.*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. // adding buttons to the frame
17. f.add(b1); f.add(b2); f.add(b3);
18. f.add(b4); f.add(b5); f.add(b6);
19. f.add(b7); f.add(b8); f.add(b9);
20. // setting grid layout of 3 rows and 3 columns
21. f.setLayout(new GridLayout(3,3));
22. f.setSize(300,300);
23. f.setVisible(true);
24. }
25. public static void main(String[] args) {
26. new MyGridLayout();
27. }
28. }
Output:
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
• FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment and a default
5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
1. import java.awt.*;
2. import javax.swing.*;
3. public class MyFlowLayout{
4. JFrame f;
5. MyFlowLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. // adding buttons to the frame
13. f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
14. // setting flow layout of right alignment
15. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
16. f.setSize(300,300);
17. f.setVisible(true);
18. }
19. public static void main(String[] args) {
20. new MyFlowLayout();
21. }
22. }
Output:
Java CardLayout
The Java 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.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.
CardLayoutExample
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class CardLayoutExample2 extends JFrame implements ActionListener{
5. CardLayout card;
6. JButton b1,b2,b3;
7. Container c;
8. CardLayoutExample2(){
9. c=getContentPane();
10. card=new CardLayout(40,30);
11. //create CardLayout object with 40 hor space and 30 ver space
12. c.setLayout(card);
13. b1=new JButton("Apple");
14. b2=new JButton("Boy");
15. b3=new JButton("Cat");
16. b1.addActionListener(this);
17. b2.addActionListener(this);
18. b3.addActionListener(this);
19. c.add("a",b1);c.add("b",b2);c.add("c",b3);
20. }
21. public void actionPerformed(ActionEvent e) {
22. card.next(c);
23. }
24. public static void main(String[] args) {
25. CardLayoutExample2 cl=new CardLayoutExample2();
26. cl.setSize(400,400);
27. cl.setVisible(true);
28. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
29. }
30. }
Output:
GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of the 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
the constraints object, we arrange the component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine the component's size. GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes and can occupy multiple rows or columns.
Constructor
Example Program:
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41. }
42. }
Output: