F21SF Software Engineering Foundations Interaction with a GUI Dept of Computer Science 10/04/2015 Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision Interaction with GUI 1 Topics Event handling in java with buttons Dialogs Validating user input 10/04/2015 Interaction with GUI 2 F21SF Software Engineering Foundations JOptionPane Dialog Dept of Computer Science 10/04/2015 Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision Interaction with GUI 3 JOptionPane JOptionPane is an example of a dialog box. It is used to get limited information from the user Displays a message Either Yes/No or OK/Cancel Maybe simple text input It is modal. This means that once it is displayed, the user has to interact with it before they can do anything else with the application. 10/04/2015 Interaction with GUI 4 JOptionPane examples - 1 The simplest version displays a message JOptionPane.showMessageDialog(null, "Goodbye"); The first parameter is often ‘null’, meaning that the message is not attached to a parent Component, such as a JFrame. 10/04/2015 Interaction with GUI 5 JOptionPane examples - 2 An input dialog gets text from the user If the user presses cancel, the value returned is null String speed = JOptionPane.showInputDialog(null, "Speed in miles per hour?"); 10/04/2015 Interaction with GUI 6 Validating input You could use this for any input, not just JOptionPanes try { double mph = Double.parseDouble(speed); double kph = 1.621 * mph; JOptionPane.showMessageDialog(null, "KPH = " + kph); finish = true; } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "'" + speed + "' is not a number", "Invalid input", JOptionPane.ERROR_MESSAGE ); } 10/04/2015 Interaction with GUI 7 JOptionPane examples - 3 This example sets the title & changes the icon JOptionPane.showMessageDialog(null, "'" + speed + "' is not a number", "Invalid input", JOptionPane.ERROR_MESSAGE ); 10/04/2015 Interaction with GUI 8 JOptionPane - summary You can Show a message, input or confirm dialog box Link the dialog to a parent component, such as a frame, or not (essential) Provide a message (essential) Provide a title (optional) Change the default set of option buttons (optional) Change the style of the message (optional) Includes a default icon (warning, error etc ) For more details See java tutorial and java documentation My example provided on Vision 10/04/2015 Interaction with GUI 9 F21SF Software Engineering Foundations Back to buttons Dept of Computer Science 10/04/2015 Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision Interaction with GUI 10 User Interface Events There are many user interface events. Today we are interested in button clicks Other events might be…… Mouse pressed, released, clicked, dragged,... Text value changed Window closed, activated Check box, list box, combo box changed etc 10/04/2015 Interaction with GUI 11 An Event-driven program An event driven program waits for an event and then reacts to it The user, not the programmer, controls the order in which events occur This is the natural model for a program with a GUI The programmer specifies which events they wish to handle Events which are not handled are ignored The java.awt.event package is used to Listen for events Transfer control to the correct place in the program 10/04/2015 Interaction with GUI 12 Java Event Handling Model is registered to Button Event source listen for ActionEvent Listening Class Event handler fires action event passes action event details to Operating System 10/04/2015 Interaction with GUI 13 The event source The event source (e.g. Button) Can generate the event (e.g. button clicks) JButton search; search = new JButton("Search"); Manages the listeners – knows which class contains the methods which will handle the event The method-handling class is specified using the addActionListener method In our case, the method which handles the event will be in the same class i.e. the GUI class, and is referred to as ‘this’ search.addActionListener(this) ; 10/04/2015 Interaction with GUI 14 The listeners The event listener class must provide standard methods to handle the event The class does this by implementing the appropriate Listener interface For JButtons, there is an ActionListener interface This interface describes the required method actionPerformed which handles button clicks. All the information about the button click is provided in an ActionEvent object, which is a parameter to the actionPerformed method. 10/04/2015 Interaction with GUI 15 actionPerformed method In the StaffList example, our frame class implements the interface and provides the actionPerformed method. public class StaffListGUI extends JFrame implements ActionListener { . . . public void actionPerformed(ActionEvent e) { if (e.getSource() == showListById) { displayList.setText(staffList.listByID()); } else if (e.getSource() == showListByName ) { displayList.setText(staffList.listByName()); } else if (e.getSource() == search) { . . . } } 10/04/2015 Interaction with GUI 16 Java Event Model A typical program System calls the main method Nothing happens until the user causes an event Main method calls constructors to set up the GUI Main terminates System calls the listener method Listener method handles the event and terminates Nothing happens until the next event..... 10/04/2015 Interaction with GUI 17 What can go wrong with listeners? What if you do not register the listener class with the button? (i.e. no addActionListener ) What if your GUI class implements ActionListener, but does not have an actionPerformed method? What if you provide the actionPerformed method and do not implement ActionListener? What if you forget to import the java.awt.event package? 10/04/2015 Interaction with GUI 18 Listener problems – answers - 1 What if you do not register the listener class with the button? (i.e .no addActionListener ) Nothing happens when you click on the button What if your GUI class implements ActionListener, but does not have an actionPerformed method? Compilation error, if the class implements an interface, it must provide the required methods 10/04/2015 Interaction with GUI 19 Listener problems - answers What if you provide the actionPerformed method and do not implement ActionListener? If you don’t add actionListeners either, the actionPerformed method is just another method in your class, but will never be called If you do add actionListeners, the compiler recognises that your class doesn’t implement ActionListener, and complains. What if you forget to import the java.awt.event package? The compiler doesn’t recognise any of the event handling classes and interfaces and their methods 10/04/2015 Interaction with GUI 20 Summary : Enabling a GUI class to handle ActionEvents Import java.awt.event.* Add implements ActionListener to the class header use the addActionListener method for each component that is to fire an event: myButton.addActionListener(this) write an actionPerformed (ActionEvent e) method containing the event handling code. You may need to determine which event occurred. if (e.getSource() == myButton) 10/04/2015 Interaction with GUI 21 StaffList application StaffList Demo StaffList Interface JFrame StaffListGUI StaffList Staff 10/04/2015 Action Listener Other Awt and swing classes N.B. StaffList and Staff classes could be used by different interface => Flexible design Interaction with GUI 22 Closing an application Sometimes you want to do some final processing just before closing. Disable the window closing button setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE); Add your own button to the GUI close = new JButton("Close"); close.addActionListener(this); northPanel.add(close); Do whatever you like when the user presses it. else if (e.getSource() == close) { JOptionPane.showMessageDialog(this, "Do 'end of program' things instead of showing this"); System.exit(0); } 10/04/2015 Interaction with GUI 23 Getting data from text fields If the user inputs data, you get it from the text field and check that it is ok String searchString = searchField.getText().trim(); if(searchString.length() > 0) { Staff person = staffList.findById(searchString); if (person != null ) result.setText(person.toString()); else result.setText("not found"); } else result.setText("no text entered"); 10/04/2015 Interaction with GUI 24 More data validation You may need to convert a string to a number Recall Integer.parseInt discussed under File IO See update method in StaffListGUI2 Or check ranges using if/else ...... You could use a try/catch 10/04/2015 Interaction with GUI 25 Summary These 2 lectures provide examples of: Organising layout Closing the application from a GUI Displaying in text areas, labels, text fields Using JOptionPane methods Responding to button clicks Getting data from a text area You should be able to study the supplied code and use a similar approach in your assignment 10/04/2015 Interaction with GUI 26