EE2E1. JAVA Programming: Event Handling and Building User Interfaces With Swing
EE2E1. JAVA Programming: Event Handling and Building User Interfaces With Swing
JAVA Programming
Lecture 6
Selection boxes
Dialog boxes
etc
Listener
object 2
click
Event source
push
Push button
Listener
push object 3
In terms of Java objects and methods, event
handling works as follows :
An event source registers all listener
objects
The event source sends out event objects
to all registered listener objects
Each listener object uses information
encapsulated in the event object to call
the appropriate listener method
The following example shows a simple user
interface to select the background colour
This has been implemented as an applet so that
it can be run with a web browser
The normal JFrame class has been replaced
with a JApplet class
Other small changes required
http://www.eee.bham.ac.uk/spannm/Java%20St
uff/ButtonTestApplet/ButtonTestApplet.html
Class ButtonPanel is the panel containing the
push buttons and the event handling (key parts
emboldened)
class ButtonPanel extends JPanel implements
ActionListener
{
public ButtonPanel()
{
// Create buttons and add listeners
}
ButtonPanel
ButtonPanel.actionPerformed(ActionEvent evt) is
called automatically when one of the buttons is
pressed
evt is an ActionEvent object which can be used
to determine which of the buttons was pressed
the event
Object is the super class so an object of any
class can be assigned to it
Event classes
Event classes are arranged in an inheritance
tree with the base class being EventObject
Event classes are in the package
java.awt.event
Event objects encapsulate information about
the event such as the event source
Each event class has a corresponding event
listener class
We have already seen two examples of events and
corresponding listeners
ActionEvent with listener ActionListener
generated by (amongst other things) a button
press
WindowEvent with listener WindowListener
generated when a user tries to close a window
Events are also generated by keyboard presses and
mouse drags and clicks which are handled by
appropriate listeners
Some events (such as a PaintEvent) are generated
automatically when a window is moved/resized so
that it is repainted
Example a mouse tracker
A mouse tracker program keeps track of the
motion of the mouse and mouse clicks
Uses event listeners
MouseListener
MouseMotionListener
mousePressed
mouseReleased
mouseEntered
mouseExited
mouseClicked
MouseMotionListener
Methods :
mouseDragged
mouseMoved
http://www.eee.bham.ac.uk/spannm/Java%2
0Stuff/MouseTrackerApplet/MouseTracker
Applet.html
The program has been implemented as an
applet
The implementation of the event handlers is
straighforward
Uses event.getX() and event.getY() to
determine the mouse position
mouseEntered() puts up a diaglog box
Labels
JLabel
Buttons
JButton
JCheckBox
Radio buttons (for choosing 1 from several
options)
JRadioButton
Lists
JList
JComboBox
Scroll bars
JScrollBar
Menus ( a bit more involved)
JMenuBar, JMenu, JMenuItem
Diaog boxes (quite a bit more involved!)
JOptionPane
File chooser dialog box (very useful!)
JFileChooser
We will implement a couple of examples of
creating GUIs containing some of these
components
You can see all of these components in action
(plus a few more) at
http://www.eee.bham.ac.uk/spannm/Java%20St
uff/SwingSetApplet/SwingSetApplet.html
Before we start building simple GUIs, it is
important to know about layout management (how
GUI components are spatially arranged)
Layout within a GUI layout
managers
Layout managers control how GUI
components are spatially arranged within a
container
Its important to understand the basics of
layout even though many development
environments come with pick and place
type layout tools
Flow layout
We have seen how we created a simple GUI by
adding buttons to a panel
The default layout manager for panels is a flow
layout manager
Components (such as buttons) are arranged left
to right top to bottom
When the panel is re-sized, the buttons are re-
flowed to fill the space
More buttons are added to the right of the
existing row and a new row of buttons is started
if there is no more space for the current row
Yellow Blue Red
Orange Purple ..
Border layout
This is the default layout manager for the JFrame
class
Partitions the available space
North
South
I want to be
Bold Italic 10
The following is the code for the actionPerformed()
method of the outer JFrame (or JApplet) class
mbar.add(ShapeMenu);
JMenu JMenuBar
Shape
Draw Rectangle
JMenuItem
Draw Oval
The event handler for selecting a menu item is also
straightforward
A separate DrawPanel class is defined with a
draw() method
class DrawPanel extends JPanel
{
public void setColour(Color c) {}
public void paintComponent(Graphics g) {}
public void setSize(int size) {}
public void draw(int drawShape) {}
}
Methods draw(), setSize() and setColour() set the
current shape, size and colour and then call repaint()
which automatically calls paintComponent()
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() instanceof JMenuItem)
{
String arg=evt.getActionCommand();
if (arg.equals("Draw Rectangle"))
{
/***
* Draw a rectangle
***/
panel.draw(DrawPanel.RECTANGLE);
}
else if (arg.equals("Draw Oval"))
{
/***
* Draw an oval
***/
panel.draw(DrawPanel.OVAL);
}
}
}
The list and slider are added using the following
code
shapeColourList=new JList(colorNames);
sizeSlider=new JSlider(SwingConstants.HORIZONTAL,
0,200,100);
sizeSlider.setMajorTickSpacing(20);
sizeSlider.setPaintTicks(true);
JPanel ColourListPanel=new JPanel();
ColourListPanel.add(new JScrollPane(shapeColourList));
container.add(ColourListPanel,"East");
container.add(sizeSlider,"South");
ColourNames is an string array of colours
{Black, Blue, Cyan .}
The final step is to add event handlers for
the list and slider
The listener for list selection events is
ListSelectionListener
The listener for slider events is
ChangeListener
Have created listeners as anonymous inner
classes
An alternative to having the outer frame
(or applet) as the listener
shapeColourList.addListSelectionListener(
// anonymous inner class
new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent evt)
{
panel.setColour(colors[shapeColourList.getSelectedIndex()]);
}
}
);
sizeSlider.addChangeListener(
//anonymous inner class
new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
panel.setSize(sizeSlider.getValue());
}
}
);
The valueChanged() and stateChanged() methods
of the ListSelectionListener and ChangeListener
interfaces respectively are defined inside the inner
class
A key point is that methods inside inner classes
can access the private instance fields of objects of
the outer class
panel is private instance field of the outer class
The syntax looks messy but you soon get used to
it!
JFrame (JApplet) object
object implementing
ListSelectionListener interface
public valueChanged() {}
Can access