13 2 Event Handling and Layout Managers
13 2 Event Handling and Layout Managers
13 2 Event Handling and Layout Managers
Managers
1
Java
Contents
2
Java
Contents
12 Adapters
13 WindowAdapter
14 ItemListener and ItemEvent
15 MouseListener and MouseEvent
16 Layout Manager Classes
17 FlowLayout
18 Constructors and Methods
19 BorderLayout
20 Constructors and Methods
21 GridLayout
22 Constructors and Methods
23 Null Layout Manager
3
Java
Know
• 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
Anu myself as a club
member so that
when an event
happens, the club
informs me.
Inter Club
Annual Sports
Sports
Event
I run Event
6
Java
Anu
Annual event
happening .
Please run.
Inter Club
Annual Sports
Sports
Event
I run Event
7
Java
Java terminology
Anu
Listeners objects
Source object
Raj Event object
Inter Club
Annual Sports
Sports
Event
Event
8
Java
Anu
Source(Ex. JButton)
2. Generates events
(user clicks)
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
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
EventObject
•Root class for all event objects
•Object getSource()
14
Java
Listeners
• 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 ActionListener
• InputMethodEvent InputMethodListener
• ChangeEvent ChangeListener
• WindowEvent WindowListener
• ItemEvent ItemListener
• ListSelectionEvent 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?
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
Example
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");
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
23
Java
If you don’t mind can we handle the frame
close event. I am tried of pressing control-C.
Sure!
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.
26
Java
Adapters
•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
WindowAdapter
• 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.
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.
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()
ItemEvent.SELECTED
ItemEvent.DESELECTED
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);}
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.*;
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
FlowLayout
• 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
BorderLayout
• 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)
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
Java
GridLayout
• 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.
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
p.add(new JLabel("Login")); 54
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.
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
JPasswordField(20); Example 7
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