EE2E1 Lecture 6 old

Download Report

Transcript EE2E1 Lecture 6 old

EE2E1. JAVA Programming
Lecture 6
Event handling and building user
interfaces with Swing
Contents









Introduction
Java’s event delegation model – event sources and
event listeners
Event classes
Example – a mouse tracker
Building GUI’s
Layout within a GUI – layout managers
Example 1
Example 2
And finally……..how do we build our own
GUI’s?
Introduction



Most modern applications come with a
sophisticated user interface comprising
 Push buttons
 Selection boxes
 Dialog boxes
 Pull down menus
 etc
Interacting with a user interface component
generates an event which must be handled by the
application program
Therefore, in order to be able to create our own user
interfaces, we must understand the Java event
model
Java’s event delegation model –
event sources and event listeners

Different languages handle event programming in
different ways

In Visual Basic, each user interface component
generates a specific event which a particular piece
of code handles


Simple but rather inflexible
In C, all events are treated equally and added to an
event queue for processing

Complex to code and requires access to the
event queue


Java allows objects to be designated event
listeners which can listen for for specific types of
events (for example a mouse button click)

Unlike VB, the listener is not predetermined

Unlike C, objects have to only handle specific
types of events
The diagram below shows how objects are
designated listeners for specific event sources

Event listeners are registered with the particular
event sources whose events they handle

One object can be a listener for several sources
Event source
click
Mouse button
click
Listener
object 1
Listener
object 2
Event source
push
Push button
push
Listener
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
}
public void actionPerformed(ActionEvent evt)
{
// Handle button press events
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
blueButton = new JButton("Blue");
redButton = new JButton("Red");
add(yellowButton);
add(blueButton);
add(redButton);
}
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
setBackground(color);
repaint();
}

class ButtonPanel extends JPanel implements
ActionListener


The panel object implements the ActionListener
interface and an implementation of the method
ActionPerformed(), which is the event handling
method which must be provided
yellowButton.addActionListener(this);

The JButton object yellowButton registers the
ButtonPanel object as a listener for button
presses
yellowButton.addActionListener(this)
Yellow
Blue
ButtonPanel
Red

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

Object source = evt.getSource();
 This returns the object which was the source of
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
 Listens for mouse button clicks
 MouseMotionListener
 Listens for mouse moves and drags
We need to implement the following methods in
the listener interfaces


MouseListener interface
 Methods :
 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
(see later) so that the user can select when
ready to track

public class MouseTrackerApplet extends JApplet implements
MouseListener, MouseMotionListener
{
public MouseTrackerApplet()
{
getContentPane().add(new Jlabel(), BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent event) {..}
public void mousePressed(MouseEvent event) {..}
public void mouseReleased(MouseEvent event) {..}
public void mouseEntered(MouseEvent event) {..}
public void mouseExited(MouseEvent event) {..}
public void mouseDragged(MouseEvent event) {..}
public void mouseMoved(MouseEvent event) {..}
.
.
}
public void mouseClicked(MouseEvent event)
{
statusBar.setText("Clicked at [" + event.getX() + ", " +
event.getY() + "]");
}
public void mouseEntered(MouseEvent event)
{
if (!entered)
{
JOptionPane.showMessageDialog(null,"Mouse in
window");
entered=true;
}
}
Building GUI’s

Swing has a large number of classes for GUI
components
Text input
 JTextField
 Labels
 JLabel
 Buttons
 JButton
 Check boxes (for choosing options)
 JCheckBox

Radio buttons (for choosing 1 from several
options)
 JRadioButton
 Lists
 JList
 Drop down boxes (combo boxes)
 JComboBox
 Scroll bars
 JScrollBar


Menus ( a bit more involved)


Diaog boxes (quite a bit more involved!)


JMenuBar, JMenu, JMenuItem
JOptionPane
File chooser dialog box (very useful!)

JFileChooser

We will implement a couple of examples of
creating GUI’s 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 GUI’s, 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 ‘reflowed’ 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
Orange
Blue
Purple
Red
…..
Border layout


This is the default layout manager for the JFrame
class
Partitions the available space
North
West Centre East
South


Unless we specify, components are added to the
centre partition
Normal to add buttons etc. to panels in flow layout
and then add the panels to the outer frame
More sophisticated layout managers

We can specify more precise positioning of GUI
components
 Grid layout
 Components arranged in rows and columns
(for example, calculator buttons)
 Grid Bag layout
 Flexible grid layout where rows columns can
have variable sizes
 Box layout
 Layout comprises a single row (column) for
a horizontal (vertical) box
Example 1
A GUI to select the font size and style of a
label string
 Uses a check box to select bold/italic
 Uses a combo box to select font size
 http://www.eee.bham.ac.uk/spannm/Java%2
0Stuff/FontChangeApplet/FontChangeAppl
et.html


The following code adds the check box and
combo box to a panel
JPanel p = new JPanel();
JCheckBox bold = new JCheckBox("Bold");
bold.addActionListener(this);
p.add(bold);
JCheckBox italic= new JCheckBox(“Italic");
italic.addActionListener(this);
p.add(italic);
JComboBox fontsize = new JComboBox();
fontsize.setEditable(true);
fontsize.addItem("10");
fontsize.addItem("16");
fontsize.addItem("20");
fontsize.addActionListener(this);
p.add(fontsize);


A second FontChangePanel contains the string
 Every time the font is changed, repaint() is
called to repaint the string in the panel
The two panels are added to the centre and south
portion of the frame
getContentPane().add(p, "South");
panel = new FontChangePanel();
getContentPane().add(panel, "Center");
I want to be …
Bold
Italic
10

The following is the code for the actionPerformed()
method of the outer JFrame (or JApplet) class

JComboBox.getSelectedItem() returns the item
selected (it is of type Object so has to be cast to a
string)

JCheckBox.isSelected() returns the state of the
checkbox (true for selected, false otherwise)

font and size are fields of the outer JFrame (or
JApplet) which hold the current font and fontsize of
the string
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
if (source==fontsize)
{
String fsize=(String)
((JComboBox)source).getSelectedItem();
size=Integer.valueOf(fsize).intValue();
panel.setFont(font, size);
}
else
{
font=(bold.isSelected() ? Font.BOLD : 0) +
(italic.isSelected() ? Font.ITALIC : 0);
panel.setFont(font,size);
}
}
Example 2

A simple shape drawing/manipulation GUI

Uses :

A menu button to select the shape

A list to select the colour

A slider to select the size

This GUI could be the basis of a more sophisticated
drawing package

http://www.eee.bham.ac.uk/spannm/Java%20Stuff/
DrawShapesApplet/DrawShapesApplet.html

Code to add the menu is straightforward
JMenuBar mbar=new JMenuBar();
setJMenuBar(mbar);
JMenu ShapeMenu=new JMenu("Shape");
JMenuItem RectItem=new JMenuItem("Draw Rectangle");
RectItem.addActionListener(this);
ShapeMenu.add(RectItem);
ShapeMenu.addSeparator();
JMenuItem OvalItem=new JMenuItem("Draw Oval");
OvalItem.addActionListener(this);
ShapeMenu.add(OvalItem);
ShapeMenu.addSeparator();
mbar.add(ShapeMenu);
JMenu
JMenuBar
Shape
Draw Rectangle
Draw Oval
JMenuItem

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
private DrawPanel panel;
.
.
And finally……..how do we build
our own GUI’s?

There has been a lot of detail in this lecture

There are dozens of GUI component classes and
hundreds of methods which we can’t possibly
hope to memorise

How do we build our own GUI’s?


‘Drag and drop’ GUI builders are becoming a
feature of Java IDE’s
Using JavaBeans enables powerful
functionality to be added

The swing component set web page is a
useful ‘online’ help for finding out about
GUI classes and methods
 http://java.sun.com/docs/books/tutorial/ui
swing/components/components.html