Download presentation
Presentation is loading. Please wait.
Published byGeorge White Modified over 9 years ago
1
EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing
2
Contents Introduction Introduction Java’s event delegation model – event sources and event listeners Java’s event delegation model – event sources and event listeners Event classes Event classes Example – a mouse tracker Example – a mouse tracker Building GUI’s Building GUI’s Layout within a GUI – layout managers Layout within a GUI – layout managers Example Example And finally……..how do we build our own GUI’s? And finally……..how do we build our own GUI’s?
3
Introduction Most modern applications come with a sophisticated user interface comprising 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” 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
4
Introduction Scroll bar Textbox Menu itemCombo box Button Label Frame Menu bar
5
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 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 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) 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
6
Mouse button Push button clickListener object 1 Listener object 2 click push Listener object 3 push Event source
7
In terms of Java objects and methods, event handling works as follows : 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
8
8 Three Parts of a GUI Application 1. Components that make up the Graphical User Interface 2. Listeners that receive the events and respond to them 3. Application code that does useful work for the user
9
The following example shows a simple user interface to select the background colour 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 http://www.eee.bham.ac.uk/spannm/Java%20St uff/ButtonTestApplet/ButtonTestApplet.html 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)
10
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; }
11
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); }
12
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(); }
13
Blue Red Yellow yellowButton.addActionListener(this) ButtonPanel
14
Event classes Event classes are arranged in an inheritance tree with the base class being EventObject Event classes are arranged in an inheritance tree with the base class being EventObject Event classes are in the package java.awt.event Event classes are in the package java.awt.event Event objects encapsulate information about the event such as the event source Event objects encapsulate information about the event such as the event source Each event class has a corresponding event listener class Each event class has a corresponding event listener class
15
We have already seen two examples of events and corresponding listeners 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 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 Some events (such as a PaintEvent) are generated automatically when a window is moved/resized so that it is repainted
16
16 Events Generated by Swing Components Act that results in the eventListener 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
17
Example – a mouse tracker A mouse tracker program keeps track of the motion of the mouse and mouse clicks A mouse tracker program keeps track of the motion of the mouse and mouse clicks Uses event listeners 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 We need to implement the following methods in the listener interfaces
18
MouseListener interface MouseListener interface Methods : mousePressed mouseReleased mouseEntered mouseExited mouseClicked MouseMotionListener MouseMotionListener Methods : mouseDragged mouseMoved
19
http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/MouseTrackerApplet/MouseTracker Applet.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/MouseTrackerApplet/MouseTracker Applet.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/MouseTrackerApplet/MouseTracker Applet.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/MouseTrackerApplet/MouseTracker Applet.html
20
The program has been implemented as an applet The program has been implemented as an applet The implementation of the event handlers is straighforward The implementation of the event handlers is straighforward Uses event.getX() and event.getY() to determine the mouse position mouseEntered()puts up a dialogbox so that the user can select when ready to track mouseEntered() puts up a dialog box so that the user can select when ready to track
21
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) {..}. }
22
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; }
23
Building GUI’s Swing has a large number of classes for GUI components Swing has a large number of classes for GUI components Text input JTextField Labels JLabel Buttons JButton Check boxes (for choosing options) JCheckBox
24
Radio buttons (for choosing 1 from several options) JRadioButton Lists JList Drop down boxes (combo boxes) JComboBox Scroll bars JScrollBar
25
Menus ( a bit more involved) JMenuBar, JMenu, JMenuItem Diaog boxes (quite a bit more involved!) JOptionPane File chooser dialog box (very useful!) JFileChooser
26
26 Dialog Boxes Used by applications to interact with the user Used by applications to interact with the user Provided by Java’s JOptionPane class Provided by Java’s JOptionPane class Contains input dialogs and message dialogs
27
27 Dialog Boxes Note icon Note icon Other icons available Other icons available
28
You can see all of these components in action (plus a few more) at 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 http://www.eee.bham.ac.uk/spannm/Java%20St uff/SwingSetApplet/SwingSetApplet.html 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) Before we start building simple GUI’s, it is important to know about layout management (how GUI components are spatially arranged)
29
Layout within a GUI – layout managers Layout managers control how GUI components are spatially arranged within a container 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 Its important to understand the basics of layout even though many development environments come with ‘pick and place’ type layout tools
30
Flow layout We have seen how we created a simple GUI by adding buttons to a panel 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 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
32
Border layout This is the default layout manager for the JFrame class This is the default layout manager for the JFrame class Partitions the available space Partitions the available space Unless we specify, components are added to the centre partition 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 Normal to add buttons etc. to panels in flow layout and then add the panels to the outer frame
33
More sophisticated layout managers We can specify more precise positioning of GUI components 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
34
Here are several common Java layout managers: Here are several common Java layout managers: Layout managers
35
35 Complex layouts How would you create a complex window like this, using the layout managers shown? How would you create a complex window like this, using the layout managers shown?
36
create panels within panels create panels within panels each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved example: example: how many panels? what layout in each? Solution: composite layout
37
Example A GUI to select the font size and style of a label string A GUI to select the font size and style of a label string Uses a check box to select bold/italic Uses a check box to select bold/italic Uses a combo box to select font size Uses a combo box to select font size http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/FontChangeApplet/FontChangeAppl et.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/FontChangeApplet/FontChangeAppl et.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/FontChangeApplet/FontChangeAppl et.html http://www.eee.bham.ac.uk/spannm/Java%2 0Stuff/FontChangeApplet/FontChangeAppl et.html
38
The following code adds the check box and combo box to a panel 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);
39
A second FontChangePanel contains the string 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 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
40
The following is the code for the actionPerformed() method of the outer JFrame (or JApplet) class 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) 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) 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 font and size are fields of the outer JFrame (or JApplet) which hold the current font and fontsize of the string
41
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); }
42
And finally……..how do we build our own GUI’s? There has been a lot of detail in this lecture 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 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? 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
43
The swing component set web page is a useful ‘online’ help for finding out about GUI classes and methods The swing component set web page is a useful ‘online’ help for finding out about GUI classes and methods Swing tutorial Swing tutorial Swing tutorial
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.