ee2e1. java programming lecture 6 event handling and building user interfaces with swing

43
EE2E1. JAVA Programming Lecture 6 Lecture 6 Event handling and building user Event handling and building user interfaces with Swing interfaces with Swing

Upload: george-white

Post on 05-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

EE2E1. JAVA Programming

Lecture 6Lecture 6

Event handling and building user Event handling and building user interfaces with Swinginterfaces with Swing

Page 2: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Contents IntroductionIntroduction Java’s event delegation model – event sources Java’s event delegation model – event sources

and event listenersand event listeners Event classesEvent classes Example – a mouse trackerExample – a mouse tracker Building GUI’sBuilding GUI’s Layout within a GUI – layout managersLayout within a GUI – layout managers ExampleExample And finally……..how do we build our own And finally……..how do we build our own

GUI’s?GUI’s?

Page 3: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Introduction Most modern applications come with a sophisticated user interface Most modern applications come with a sophisticated user interface

comprisingcomprising Push buttonsPush buttons Selection boxesSelection boxes Dialog boxesDialog boxes Pull down menusPull down menus etcetc

GUI’s gives an application a distinctive “look” and “feel”GUI’s gives an application a distinctive “look” and “feel” Provides users with basic level of familiarityProvides users with basic level of familiarity Built from GUI components (controls, widgets, etc.)Built from GUI components (controls, widgets, etc.)

User interacts with GUI component via mouse, keyboard, etcUser interacts with GUI component via mouse, keyboard, etc

Page 4: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Introduction

Scroll bar

Textbox

Menu itemCombo box

Button

Label

Frame

Menu bar

Page 5: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Java’s event delegation model – event sources and event listeners Interacting with a user interface component generates Interacting with a user interface component generates

an an eventevent which must be handled by the application which must be handled by the application programprogram

Therefore, in order to be able to create our own user Therefore, in order to be able to create our own user interfaces, we must understand the Java interfaces, we must understand the Java event modelevent model

Java allows objects to be designated Java allows objects to be designated event listenersevent listeners which can listen for which can listen for specific specific types of events (for types of events (for example a mouse button click)example a mouse button click) Event listeners are Event listeners are registeredregistered with the particular with the particular

event sourcesevent sources whose events they handle whose events they handle

One object can be a listener for several sourcesOne object can be a listener for several sources

Page 6: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Mouse button

Push button

click Listener object 1

Listener object 2

click

push

Listener object 3push

Event source

Event source

Page 7: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

In terms of Java objects and methods, event In terms of Java objects and methods, event handling works as follows :handling works as follows :

An event source registers all listener An event source registers all listener objectsobjects

The event source sends out The event source sends out event objectsevent objects to all registered listener objectsto all registered listener objects

Each listener object uses information Each listener object uses information encapsulated in the event object to call encapsulated in the event object to call the appropriate listener methodthe appropriate listener method

Page 8: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

8

Three Parts of a GUI Application

1.1. Components that make up the Graphical Components that make up the Graphical User Interface User Interface

2.2. Listeners that receive the events and Listeners that receive the events and respond to them respond to them

3.3. Application code that does useful work for Application code that does useful work for the user the user

Page 9: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

The following example shows a simple user interface to select The following example shows a simple user interface to select the background colourthe background colour

This has been implemented as an applet so that it can be run This has been implemented as an applet so that it can be run with a web browserwith a web browser

The normal The normal JFrame JFrame class has been replaced with a class has been replaced with a JApplet JApplet classclass

Other small changes requiredOther small changes required

http://www.eee.bham.ac.uk/spannm/Java%20Stuff/http://www.eee.bham.ac.uk/spannm/Java%20Stuff/ButtonTestApplet/ButtonTestApplet.html ButtonTestApplet/ButtonTestApplet.html

Class Class ButtonPanel ButtonPanel is the panel containing the push buttons is the panel containing the push buttons and the event handling (key parts emboldened)and the event handling (key parts emboldened)

Page 10: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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;}

Page 11: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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);}

Page 12: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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();}

Page 13: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Blue RedYellow

yellowButton.addActionListener(this)

ButtonPanel

Page 14: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Event classes Event classes are arranged in an inheritance Event classes are arranged in an inheritance

tree with the base class being tree with the base class being EventObjectEventObject Event classes are in the package Event classes are in the package

java.awt.eventjava.awt.event Event objects encapsulate information Event objects encapsulate information

about the event such as the event sourceabout the event such as the event source Each event class has a corresponding event Each event class has a corresponding event

listener classlistener class

Page 15: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

We have already seen two examples of events and We have already seen two examples of events and corresponding listenerscorresponding listeners ActionEventActionEvent with listener with listener ActionListenerActionListener generated generated

by (amongst other things) a button pressby (amongst other things) a button press WindowEventWindowEvent with listener with listener WindowListenerWindowListener

generated when a user tries to close a windowgenerated when a user tries to close a window Events are also generated by keyboard presses and Events are also generated by keyboard presses and

mouse drags and clicks which are handled by mouse drags and clicks which are handled by appropriate listenersappropriate listeners

Some events (such as a Some events (such as a PaintEventPaintEvent) are generated ) are generated automatically when a window is moved/resized so automatically when a window is moved/resized so that it is repaintedthat it is repainted

Page 16: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

16

Events Generated by Swing ComponentsAct 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

Page 17: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Example – a mouse tracker A mouse tracker program keeps track of the motion A mouse tracker program keeps track of the motion

of the mouse and mouse clicksof the mouse and mouse clicks Uses event listenersUses event listeners

MouseListenerMouseListenerListens for mouse button clicksListens for mouse button clicks

MouseMotionListenerMouseMotionListenerListens for mouse moves and dragsListens for mouse moves and drags

We need to implement the following methods in the We need to implement the following methods in the listener interfaceslistener interfaces

Page 18: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

MouseListenerMouseListener interface interface Methods :Methods :

mousePressedmousePressedmouseReleasedmouseReleasedmouseEnteredmouseEnteredmouseExitedmouseExitedmouseClickedmouseClicked

MouseMotionListenerMouseMotionListener Methods :Methods :

mouseDraggedmouseDraggedmouseMovedmouseMoved

Page 19: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

http://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java%20Stuff/MouseTrackerApplet/%20Stuff/MouseTrackerApplet/MouseTrackerApplet.html MouseTrackerApplet.html

Page 20: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

The program has been implemented as an The program has been implemented as an appletapplet

The implementation of the event handlers is The implementation of the event handlers is straighforwardstraighforward Uses Uses event.getX() event.getX() and and event.getY()event.getY() to to

determine the mouse positiondetermine the mouse position mouseEnteredmouseEntered()() puts up a dialogputs up a dialog box so box so

that the user can select when ready to that the user can select when ready to tracktrack

Page 21: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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) {..}..

}

Page 22: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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; }}

Page 23: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Building GUI’s Swing has a large number of classes for GUI Swing has a large number of classes for GUI

componentscomponents Text inputText input

JTextFieldJTextField LabelsLabels

JLabelJLabel ButtonsButtons

JButtonJButton Check boxes (for choosing options)Check boxes (for choosing options)

JCheckBoxJCheckBox

Page 24: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Radio buttons (for choosing 1 from several Radio buttons (for choosing 1 from several options)options)

JRadioButtonJRadioButton ListsLists

JListJList Drop down boxes (combo boxes)Drop down boxes (combo boxes)

JComboBoxJComboBox Scroll barsScroll bars

JScrollBarJScrollBar

Page 25: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Menus ( a bit more involved)Menus ( a bit more involved)JMenuBarJMenuBar, , JMenuJMenu, , JMenuItemJMenuItem

DiaogDiaog boxes (quite a bit more involved!)boxes (quite a bit more involved!)JOptionPaneJOptionPane

File chooser dialog box (very useful!)File chooser dialog box (very useful!)JFileChooserJFileChooser

Page 26: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

26

Dialog Boxes

Used by applications to interact with the Used by applications to interact with the useruser

Provided by Java’s Provided by Java’s JOptionPaneJOptionPane class class Contains input dialogs and message Contains input dialogs and message

dialogsdialogs

Page 27: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

27

Dialog Boxes

Note iconNote icon Other icons availableOther 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

A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button.

PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.

Page 28: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

You can see all of these components in action You can see all of these components in action (plus a few more) at(plus a few more) at http://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java

%20Stuff/SwingSetApplet/%20Stuff/SwingSetApplet/SwingSetApplet.html SwingSetApplet.html

Before we start building simple GUI’s, it is Before we start building simple GUI’s, it is important to know about important to know about layout management layout management (how (how GUI components are spatially arranged)GUI components are spatially arranged)

Page 29: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Layout within a GUI – layout managers

Layout managersLayout managers control how GUI control how GUI components are spatially arranged within a components are spatially arranged within a containercontainer

Its important to understand the basics of Its important to understand the basics of layout even though many development layout even though many development environments come with ‘pick and place’ environments come with ‘pick and place’ type layout toolstype layout tools

Page 30: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Flow layout We have seen how we created a simple GUI by adding We have seen how we created a simple GUI by adding

buttons to a panelbuttons to a panel The default layout manager for panels is a The default layout manager for panels is a flow layout flow layout

managermanager Components (such as buttons) are arranged left to right Components (such as buttons) are arranged left to right

– top to bottom– top to bottom When the panel is re-sized, the buttons are ‘re-flowed’ When the panel is re-sized, the buttons are ‘re-flowed’

to fill the spaceto fill the space More buttons are added to the right of the existing row More buttons are added to the right of the existing row

and a new row of buttons is started if there is no more and a new row of buttons is started if there is no more space for the current rowspace for the current row

Page 31: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing
Page 32: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Border layout This is the default layout manager for the This is the default layout manager for the JFrame JFrame classclass Partitions the available spacePartitions the available space

Unless we specify, components are added to the centre partitionUnless we specify, components are added to the centre partition Normal to add buttons etc. to panels in flow layout and then add the panels Normal to add buttons etc. to panels in flow layout and then add the panels

to the outer frameto the outer frame

Page 33: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

More sophisticated layout managers We can specify more precise positioning of GUI componentsWe can specify more precise positioning of GUI components

Grid layoutGrid layoutComponents arranged in rows and columns (for Components arranged in rows and columns (for

example, calculator buttons)example, calculator buttons) Grid Bag layout Grid Bag layout

Flexible grid layout where rows columns can have Flexible grid layout where rows columns can have variable sizesvariable sizes

Box layoutBox layoutLayout comprises a single row (column) for a horizontal Layout comprises a single row (column) for a horizontal

(vertical) box(vertical) box

Page 34: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Here are several common Java layout Here are several common Java layout managers:managers:

Layout managers

Page 35: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

35

Complex layouts How would you create a complex window like this, using How would you create a complex window like this, using

the layout managers shown?the layout managers shown?

Page 36: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

create panels within panelscreate panels within panels each panel has a different layout, and by each panel has a different layout, and by

combining the layouts, more complex / combining the layouts, more complex / powerful layout can be achievedpowerful layout can be achieved

example:example: how many panels?how many panels? what layout in each?what layout in each?

Solution: composite layout

Page 37: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

Example

A GUI to select the font size and style of a A GUI to select the font size and style of a label stringlabel string

Uses a check box to select bold/italicUses a check box to select bold/italic Uses a combo box to select font sizeUses a combo box to select font size http://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java

%20Stuff/FontChangeApplet/%20Stuff/FontChangeApplet/FontChangeApplet.html FontChangeApplet.html

Page 38: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

The following code adds the check box and The following code adds the check box and combo box to a panelcombo 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);

Page 39: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

A second A second FontChangePanel FontChangePanel contains the stringcontains the string Every time the font is changed, Every time the font is changed, repaint() repaint() is is

called to repaint the string in the panelcalled to repaint the string in the panel The two panels are added to the centre and south The two panels are added to the centre and south

portion of the frameportion of the framegetContentPane().add(p, "South");

panel = new FontChangePanel();

getContentPane().add(panel, "Center");

I want to be …

Bold Italic 10

Page 40: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

The following is the code for the The following is the code for the actionPerformed()actionPerformed() method of the outer method of the outer JFrame JFrame (or (or JAppletJApplet)) classclass

JComboBox.getSelectedItem()JComboBox.getSelectedItem() returns the item selected (it is of type returns the item selected (it is of type Object Object so has to be cast to a string)so has to be cast to a string)

JCheckBox.isSelected()JCheckBox.isSelected() returns the state of the checkbox ( returns the state of the checkbox ( truetrue for selected, for selected, falsefalse otherwise) otherwise)

fontfont and and size size are fields of the outer are fields of the outer JFrame JFrame (or (or JAppletJApplet)) which hold the current font and fontsize of the stringwhich hold the current font and fontsize of the string

Page 41: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

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); } }

Page 42: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

And finally……..how do we build our own GUI’s? There has been a lot of detail in this lectureThere has been a lot of detail in this lecture There are dozens of GUI component classes and There are dozens of GUI component classes and

hundreds of methods which we can’t possibly hope to hundreds of methods which we can’t possibly hope to memorisememorise

How do we build our own GUI’s?How do we build our own GUI’s? ‘‘Drag and drop’ GUI builders are becoming Drag and drop’ GUI builders are becoming

commonplacecommonplace‘‘Visual’ programmingVisual’ programmingThe programmer simply adds the event handlersThe programmer simply adds the event handlers

Page 43: EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing

The swing component set web page is a The swing component set web page is a useful ‘online’ help for finding out about useful ‘online’ help for finding out about GUI classes and methodsGUI classes and methods Swing tutorialSwing tutorial