EE2E1 Lecture 6
Download
Report
Transcript EE2E1 Lecture 6
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
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
GUI’s gives an application a distinctive “look” and “feel”
Provides users with basic level of familiarity
Built from GUI components (controls, widgets, etc.)
User interacts with GUI component via mouse,
keyboard, etc
Introduction
Frame
Combo box
Menu item
Label
Menu bar
Button
Scroll bar
Textbox
Java’s event delegation model –
event sources and event listeners
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 allows objects to be designated event
listeners which can listen for specific types of
events (for example a mouse button click)
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
Three Parts of a GUI Application
1.
2.
3.
Components that make up the Graphical
User Interface
Listeners that receive the events and
respond to them
Application code that does useful work for
the user
8
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();
}
yellowButton.addActionListener(this)
Yellow
Blue
ButtonPanel
Red
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
Events Generated by Swing
Components
Act that results in the event
Listener type
User clicks a button, presses Return
while typing in a text field, or chooses a
menu item
ActionListener
User closes a frame (main window)
WindowListener
User presses a mouse button while the
cursor is over a component
MouseListener
User moves the mouse over a
component
MouseMotionListener
Component becomes visible
ComponentListener
Component gets the keyboard focus
FocusListener
Table or list selection changes
ListSelectionListener
16
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 dialog box 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
Dialog Boxes
Used by applications to interact with the
user
Provided by Java’s JOptionPane class
Contains input dialogs and message
dialogs
26
Dialog Boxes
Note icon
Other icons available
Message dialog type
Icon
Description
ERROR_MESSAGE
A dialog that indicates an error to the user.
INFORMATION_MESSAGE
A dialog with an informational message to the
user.
WARNING_MESSAGE
A dialog warning the user of a potential
problem.
QUESTION_MESSAGE
PLAIN_MESSAGE
A dialog that poses a question to the user. This
dialog normally requires a response, such as
clicking a Yes or a No button.
no icon A dialog that contains a message, but no icon.
27
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
Border layout
This is the default layout manager for the JFrame class
Partitions the available space
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
Layout managers
Here are several common Java layout
managers:
Complex layouts
35
How would you create a complex window like this, using
the layout managers shown?
Solution: composite layout
create panels within panels
each panel has a different layout, and by
combining the layouts, more complex /
powerful layout can be achieved
example:
how many panels?
what layout in each?
Example
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);
}
}
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
commonplace
‘Visual’ programming
The programmer simply adds the event
handlers
The swing component set web page is a
useful ‘online’ help for finding out about
GUI classes and methods
Swing tutorial