380 likes | 522 Views
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
E N D
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 • 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 Listener object 1 Mouse button Listener object 2 click Event source push Push button Listener object 3 push
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%20Stuff/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
Yellow yellowButton.addActionListener(this) Red Blue 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 • 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%20Stuff/MouseTrackerApplet/MouseTrackerApplet.htmlhttp://www.eee.bham.ac.uk/spannm/Java%20Stuff/MouseTrackerApplet/MouseTrackerApplet.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 dialogbox 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) • JMenuBar, JMenu, JMenuItem • Diaogboxes (quite a bit more involved!) • JOptionPane • File chooser dialog box (very useful!) • JFileChooser
You can see all of these components in action (plus a few more) at • http://www.eee.bham.ac.uk/spannm/Java%20Stuff/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 ‘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 Orange Purple Red Blue …..
North Centre East West South 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
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%20Stuff/FontChangeApplet/FontChangeApplet.html
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); • The following code adds the check box and combo box to a panel
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 10 Italic
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