Event Handling and Layout Managers

1 Java

1 2 3 4 5 6 7 8 9 The Delegation Event Model Event types Low level events Semantic events EventObject Listeners Listeners Interfaces corresponding to each Event object Registering the listener with the source What are we going to look at?

10 ActionListener and ActionEvent 11 WindowListener and WindowEvent
2 Java

12 13 14 15 16 17 18 19 20 21 22 23 Adapters WindowAdapter ItemListener and ItemEvent MouseListener and MouseEvent Layout Manager Classes FlowLayout Constructors and Methods BorderLayout Constructors and Methods GridLayout Constructors and Methods Null Layout Manager
3 Java

• How the Delegation event model works • Listeners and Adapter classes • Layout Managers

4 Java

Be able to
• Implement Listeners and Adapter classes • Use Layout Managers effectively

5 Java


I must register myself as a club member so that when an event happens, the club informs me.

I run


Club where sports event happen

I run

Inter Club Sports Event

Annual Sports Event
6 Java

Anu Annual event happening . Please run.

I run


Sports club where sports event happen

I run

Inter Club Sports Event

Annual Sports Event
7 Java

Java terminology

Listeners objects


Source object Event object Inter Club Sports Event Annual Sports Event
8 Java

Anu Register me. I have implemented Running Raj

Inviting members who can run.(Only objects which implements Running (run() method)) Source has ‘list’ of athletes objects
(Anu, Raj). Source will ensure that they have run() method. When event happens source will call anu.run() and raj.run()

Java way of handling events Annual Sports
9 Java

The Delegation Event Model
1. Registers itself to receive events Source(Ex. JButton) 2. Generates events (user clicks) Event object 3. Calls a method on the Listener and sends event object

Listener (Ex. JFrame)

10 Java

Event types
• Low level events • Examples: • Pressing keyboard buttons • Mouse clicks • Semantic events: • Examples: • Button click • Selecting an item in the list
11 Java

Low level events
• MouseEvent • KeyEvent • Generated by all the components.

12 Java

Semantic events
• JButton, JMenuItem, JRadioButton, JCheckbox, JTextField: java.awt.event.ActionEvent • JTextField ,JTextArea, JPasswordField: java.awt.event.InputMethodEvent • JTabbedPane javax.swing.event.ChangeEvent • JFrame: java.awt.event.WindowEvent • JCombo: java.awt.event.ItemEvent • JList: javax.swing.event.ListSelectionEvent
13 Java

•Root class for all event objects •Object getSource() A method in EventObject class. Which returns us the source object on which the Event initially occurred.

14 Java

• XxxListener is an interface any source would implement if it is interested in a particular Xxxevent. • A source generating an XxxEvent would allow only those components to register with it who have implemented XxxListener. • XxxListener will have one or more methods which sources interested in the vent would implement. • When event occurs the source will call the method of XxxListener for all the components who have registered with it.
15 Java

Listeners Interfaces corresponding to each Event object java.awt.event
• • • • • • ActionEvent InputMethodEvent ChangeEvent WindowEvent ItemEvent ListSelectionEvent ActionListener InputMethodListener ChangeListener WindowListener ItemListener ListSelectionListener javax.swing.event
16 Java

Registering the listener with the source
source.addXxxListener(XxxListener t) where source is any Component Xxx: could be any one of the Listener mentioned in the previous slide

17 Java

What are we going to look at?
We will look at only the below listed Events. The others are very similar. You can get all the information about Listener methods and Event methods from the API.

1.ActionListener 2.WindowListener 3.ItemListener 4.MouseListener
18 Java

ActionListener and ActionEvent
• Source that generates ActionEvent: • Button object is clicked • MenuItem object is selected • List object is double clicked • Listener: ActionListener • public void actionPerformed(ActionEvent e) • Useful ActionEvent method: • public String getActionCommand()
19 Java


On clicking 2. Red - the panel becomes Red. 3. Green - the panel becomes Green 4. Blue - the panel becomes Blue.

20 Java

import javax.swing.*; import java.awt.event.*; import java.awt.Color; public class ColorFrame extends JFrame implements ActionListener{ JPanel panel =new JPanel(); public ColorFrame (){ super("Simple Frame With Color Button"); setSize(300,300); setVisible(true); JButton red=new JButton("Red"); JButton green=new JButton("Green"); JButton blue=new JButton("Blue"); Example 1 Creating buttons
21 Java

panel.add(red); panel.add(blue); panel.add(green); getContentPane().add(panel);

Adding buttons to the panel and panel to the frame.

red.addActionListener(this); green.addActionListener(this); blue.addActionListener(this);
Register the current object with the buttons } public void actionPerformed( ActionEvent e){ if(e.getActionCommand().equals("Red")) 22 panel.setBackground(Color.red); Java

if(e.getActionCommand().equals("Green")) panel.setBackground(Color.green); if(e.getActionCommand().equals("Blue")) panel.setBackground(Color.blue); } public static void main(String str[]){ new ColorFrame(); } }

23 Java

If you don’t mind can we handle the frame close event. I am tried of pressing control-C.

24 Java

WindowListener and WindowEvent
• Source And Event: Frame close,open, minimize, maximize • Listener: WindowListener void windowClosing(WindowEvent e) void windowClosed(WindowEvent e) void windowOpened(WindowEvent e) void windowDeiconified(WindowEvent e) void windowIconified(WindowEvent e) void windowActivated(WindowEvent e) void windowDeactivated(WindowEvent e)
25 Java

You mean I will have to implement 7 methods to handle window closing event ! I think I am ok with control-C.

Surely not. Java creators knew about the programmer’s reaction to this. They created Adapter classes for rescue.
26 Java

•Adapter classes are useful when we want to override only methods we are interested in. •Adapter classes implement the the listener interfaces and provide empty implementation for all the methods defined in the interface.

27 Java

• Gives empty implementation for all WindowListener interface methods.

28 Java

I don’t understand how Adapters will help. My frame class already extends Frame. So my frame class cannot inherit from Adapter – no MULTIPLE INHERITANCE in Java.

If we implement using WindowListener, the source and the listener both are the same object. With Adapters, we delegate the event handling to WindowAdapter object. So we don’t have to inherit from Adapter class.
29 Java

//import statements public class ColorFrame extends Frame implements ActionListener{ WindowAdapter win; public ColorFrame(){ super("Simple Frame With Menu"); … win= new WindowAdapter(){
Example 2
30 Java

public void windowClosing(WindowEvent e){ System.exit(0); }}; this.addWindowListener(win); //other methods public static void main(String str[]){ new ColorFrame();} }
31 Java


Oh it has become so incredibly easy and the code also looks very professional. I use to hate inner class but I think now I have started liking it.

Having said all this about adapters just remember that we have Adapter classes only for those Listener interfaces which have more than one method. (It makes perfect sense, right!)
32 Java

ItemListener and ItemEvent
• Source And Event: Checkbox or a List item is clicked or a Choice is selected or deselected. • Listener: ItemListener public void itemStateChanged(ItemEvent e) • Interesting ItemEvent method int getStateChange()
33 Java

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorAWT extends JFrame implements ItemListener{ JComboBox colors; JPanel panel= new JPanel(); ColorAWT() { super("Item listener"); Adding items into colors=new JComboBox(); the combo box colors.addItem("Red"); Example 3 colors.addItem("Green");

34 Java

colors.addItem("Blue"); panel.add(colors); getContentPane().add(panel); setSize(200,200); setVisible(true); colors.addItemListener(this);}

public void itemStateChanged(ItemEvent ie) { String color=(String)colors.getSelectedItem(); if(color.equals("Red")) panel.setBackground(Color.RED);
35 Java

else if(color.equals("Green")) panel.setBackground(Color.GREEN); else panel.setBackground(Color.BLUE); } public static void main(String args[]){ new ColorAWT (); } }

36 Java

MouseListener and MouseEvent
• Source and event: Mouse button pressed, released etc. • Listener: MouseListener
void mouseClicked(MouseEvent e) void mouseEntered(MouseEvent e) void mouseExited(MouseEvent e) void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e)

• MouseEvent methods:
public int getX() ,public int getY()
37 Java

We certainly can use MouseAdapter instead of typing this long list of methods of MouseListerner, right!

Exactly! Lets us draw lines on the frame. Each click of the mouse will determine the start point and the end point of the line.

38 Java

import java.awt.*; import java.awt.event.*; Import javax.swing.*; public class DrawLines extends JFrame { int x1=0; int y1=0; int x2,y2; boolean firstPoint=true; DrawLines() { super("Mouse Listener"); setSize(600,600); Example 4 setVisible(true); setBackground(Color.white);
39 Java

MouseAdapter ma= new MouseAdapter(){ public void mousePressed(MouseEvent me) { if(firstPoint) { x1=me.getX();y1=me.getY() ; firstPoint=false; x2=me.getX(); y2=me.getY(); draw(); }};
40 Java



void draw(){ Graphics g= getGraphics(); g.drawLine(x1,y1,x2,y2); x1=x2; y1=y2;


public static void main(String args[]) { new DrawLines(); } }

41 Java

Layout Manager Classes
• FlowLayout: JApplet and JPanel have this as default. • BorderLayout: JFrame has this as default. • GridLayout • CardLayout • void setLayout(LayoutManager l) where LayoutManager is a super class for all the above listed Layout Managers.

42 Java

• A flow layout arranges components one after another from left to right, top to bottom. The flow direction can also be changed to right to left. • The alignment can be either left, right centered. By default it is centered. • All the examples for the applet that we have seen so far arranges the components in the flow layout.

43 Java

Constructors and Methods
FlowLayout() FlowLayout(int align) FlowLayout(int align,int hgap,int vgap)
FlowLayout.CENTER FlowLayout.LEFT FlowLayout.RIGHT

Getters and setter for alignment hgap Horizontal gap and Vertical gap vgap

44 Java

• The border layout divides the containers area into north, south, east, west and center.

45 Java

Constructors and Methods
BorderLayout() BorderLayout(int hgap, int vgap) Setters and getters for hgap and vgap

46 Java

import javax.swing.*; Example 5 import java.awt.*; import java.awt.event.*; public class BorderExample extends JFrame implements ActionListener{ JPanel colorPanel= new JPanel(); public static void main(String s[]){ new BorderExample ();} BorderExample() { JPanel buttonPanel= new JPanel(); colorPanel.setBackground(Color.white);

47 Java

setVisible(true); setSize(300,100); JButton red = new JButton("Red", new ImageIcon("red.GIF")); JButton green = new JButton("Green",new ImageIcon("green.GIF")); JButton blue = new JButton("Blue",new ImageIcon("blue.GIF")); buttonPanel.add(red); buttonPanel.add(green); buttonPanel.add(blue);
48 Java

getContentPane().add(buttonPanel, BorderLayout.NORTH); getContentPane().add(colorPanel, BorderLayout.CENTER); red.addActionListener(this); green.addActionListener(this); blue.addActionListener(this); validate(); }
49 Java

public void actionPerformed( ActionEvent e){ if (e.getActionCommand().equals("Green")) colorPanel.setBackground(Color.green); else if (e.getActionCommand().equals("Blue")) colorPanel.setBackground(Color.blue); else colorPanel.setBackground(Color.red); validate(); } } 50


• This layout manager lays out a container's components in a rectangular grid specified by rows and columns in the constructor. • The entire area of the container is divided into grid of equal sizes.
We change our Login form that we created in swing chapter to proper format.
51 Java

Constructors and Methods
GridLayout() GridLayout(int rows, int cols) GridLayout(int rows, int cols,int hgap, int vgap) Setters and getters for hgap,vgap, rows and columns

52 Java

3 rows and 2 columns: GridLayout(3,2))

53 Java

import javax.swing.*; import java.awt.*; public class TestJFC extends JFrame { public static void main(String s[]) { new TestJFC();} TestJFC() { setVisible(true); setSize(300,120); JPanel p= new JPanel(); p.setBackground(Color.white); p.setLayout(new GridLayout(3,2)); p.setBorder(BorderFactory.createMatteBo rder(-1,-1,-1,-1,new ImageIcon("bullet.gif"))); Example 6 54 p.add(new JLabel("Login")); Java

JTextField login= new JTextField(10); p.add(login); p.add(new JLabel("Password")); JPasswordField pass= new JPasswordField(10); p.add(pass); String roles[]={"Student","Teacher","HOD","Ma nagement"}; p.add(new JLabel("Role")); JComboBox role= new JComboBox(roles); p.add(role); getContentPane().add(p); validate();}}
55 Java

What if I want to layout components and I have no layout managers that will layout in the way I want.

There are many more layout managers. But if you are not happy with any, then you can layout the components as you wish by setting the layout manager to null.
56 Java

Null Layout Manager
• • setLayoutManager(null); Use setBounds() methods void setBounds(int x, int y, int width, int height) x - the new x-coordinate of this component y - the new y-coordinate of this component width - the new width of this component height - the new height of this component

57 Java

import javax.swing.*; public class BoundsDemo extends JFrame{ public BoundsDemo(){ super("Boundslayout"); setSize(350,200); setVisible(true); getContentPane().setLayout(null); JLabel lLogin=new JLabel("Login:"); JTextField login = new JTextField(20); JLabel lPassword=new JLabel("Password:"); JPasswordField password = new Example 7 JPasswordField(20); JButton b= new JButton("Submit");

58 Java

lLogin.setBounds(30,30,100,15); login.setBounds(150,30,100,20); lPassword.setBounds(30,80,100,20); password.setBounds(150,80,100,20); b.setBounds(150,150,100,20); getContentPane().add(lLogin); getContentPane().add(login); getContentPane().add(lPassword); getContentPane().add(password); getContentPane().add(b); repaint(); }
59 Java

public static void main(String str[]){ new BoundsDemo(); } }

60 Java

Sign up to vote on this title
UsefulNot useful