Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Event Driven Programming Part 3 – Event Handling Chapter 12 CS 2334 University of Oklahoma Brian F. Veale 1 Events • All interaction with a GUI program is through events – – – – Mouse clicks Button presses Text Entry Menu selection 2 Event Handling • By default, some components appear to react to certain interaction – JScrollPanes will scroll – JButtons will change color when clicked • In order to write functional GUI programs we must handle some events • Java uses Listeners to manage event handling 3 Listeners • When we register an object as a Listener it takes responsibility for certain events – Only responsible for events from certain other components – Only responsible for a limited class of events • Listeners are actually interfaces – They are a group of methods that we agree to implement – Depending on the kind of Listener, we can have a large number of methods to implement 4 Common Listener Interfaces • ActionListener – Button being pressed – Pressing return in a text field – Selecting a menu item • MouseListener – Pressing a mouse button while over a certain component • WindowListener – Closing the main window • KeyListener – Pressing keys on the keyboard • MenuListener – Opening a menu – Selecting a menu item • More Listener Methods in the Java Tutorial – Listener API Table • http://java.sun.com/docs/books/tutorial/uiswing/events/api.htm l 5 Implementing Event Handling • Lets make it so that our GUI programs exit when we close the window – This can be annoying if not handled – Without doing this, your windows disappear, but never exit • This is going to be a window event connected to the JFrame • We’ll need to use a WindowListener – WindowListener interface has 7 methods • Every single one must be implemented – The Adapter classes comes to our rescue, maybe • You inherit from an Adapter class • It contains skeletons for all corresponding Listener methods – Difficulties • Can only inherit from one class • Not all Listeners have an Adapter • Other option is to have skeleton methods for all the parts of the interface that we won’t use 6 Exiting a Program Upon Window Closing • Which method of WindowListener should we use? – void windowActivated(WindowEvent e) • Invoked when the Window is set to be the active Window. – void windowClosed(WindowEvent e) • Invoked when a window has been closed as the result of calling dispose on the window. – void windowClosing(WindowEvent e) • Invoked when the user attempts to close the window from the window's system menu. – void windowDeactivated(WindowEvent e) • Invoked when a Window is no longer the active Window. – void windowDeiconified(WindowEvent e) • Invoked when a window is changed from a minimized to a normal state. – void windowIconified(WindowEvent e) • Invoked when a window is changed from a normal to a minimized state. – void windowOpened(WindowEvent e) • Invoked the first time a window is made visible. 7 windowClosed() or windowClosing() • void windowClosed(WindowEvent e) • Invoked when a window has been closed as the result of calling dispose on the window. • void windowClosing(WindowEvent e) • Invoked when the user attempts to close the window from the window's system menu. • Window.dispose() – Releases all of the native screen resources used by the Window. – We will not work directly with instances of Window and therefore cannot control when dispose() is called. • windowClosing() seems like the best option 8 Modifications to the Program • frame.addWindowListener(this); – The parameter is the name of the object that will handle the event – This line tells the component which object is responsible for responding to this action • Class Button extends WindowAdapter or Class Button implements WindowListener – The responding object must either extend the WindowAdapter • Only have to implement methods we’ll be using in WindowListener – or implement the WindowListener interface • Have to write at least a skeleton for all methods in WindowListener • Write a method body for the responding object 9 Demo Programs that use windowClosing() • ButtonWithWindowClosing.java • LabeledScrollingList3.java 10 ActionListener • Very high level event handler – Can avoid some of the other types of event listeners if we use ActionListener • Very common type of listener – Button presses – Menu item selection • Has a single method – public void actionPerformed(ActionEvent e) 11 Handling ActionEvents • We can make a single object the ActionListener for many other components – Must distinguish who sent the event – This data is stored in the ActionEvent object passed to actionPerformed – Methods for extracting event source info from ActionEvent • Object getSource() – Returns the object that generated the call to actionPerformed • String getActionCommand() – Returns a string that contains the text of the object – Can use setActionCommand to alter for an object – Can be used for modal buttons 12 Other methods in ActionEvent • long getWhen() – Gives us the time and date the event occurred – Can convert to human-readable with Date class • int getModifiers() – Returns data on modifier keys pressed during event (Ctrl, Shift, etc.) • String paramString() – Very useful for debugging – Presents detailed information about event in textual form 13 ActionListener Demo • ActionEvents.java 14 WindowAdapter • In ActionEvents.java, to use a WindowAdapter to close the window, we had to create an inner class. • Inner classes are a reality of life in Java GUI programs at times.... • But, is there a better way to close the window when the user clicks on the window close button? 15 public void setDefaultCloseOperation(int operation) • Sets the operation that will happen by default when the user initiates a "close" on this frame. – WindowConstants.DO_NOTHING_ON_CLOSE • Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object. – WindowConstants.HIDE_ON_CLOSE • Automatically hide the frame after invoking any registered WindowListener objects. • Default action. – WindowConstants.DISPOSE_ON_CLOSE • Automatically hide and dispose the frame after invoking any registered WindowListener objects. – JFrame.EXIT_ON_CLOSE • Exit the application using the System exit method. Use this only in applications. 16 Data Models • We can develop a data model for our program – Abstract Data Type • Our ADT can be stored in a JList • Demo 1: – LabeledScrollingList4.java – State.java • Demo 2: – StateListModel.java – LabeledScrollingList5.java 17 JList Mania • The nomenclature for Swing JLists is somewhat confusing – – – – – JList List Vector DefaultListModel ArrayList • Keeping these classes differentiated is important 18 Every JList has a data view • data view = data model • A JList is a GUI component – It shows us a view of some data • The items in the list • We tell the JList what data to show when we construct it • JLIst myList = new JList(Vector theData); • This view is not inherently dynamic – Call the constructor as above and then try to change the vector’s data – Won’t work too well (not at all) 19 Making a dynamic JList • Updating a JList – myList.setListData(Vector theNewData); • The JList will now show the current contents of the theNewData vector • Does this mean the Data model must be a Vector – It could be a Vector • Vector is part of the JCF – Can be used as a List » We can use Collections.sort() » Can use all List methods – It doesn’t have to be a Vector • Can use another JCF List type • Just make a method that returns a Vector of your List contents 20 Dynamic Lists Demo • DynamicStateLists.java 21 Clicking on a JList • There are three ways to find out which item was clicked on in a JList – myJList.getSelectedIndex() • This can work at any time • Can be in ActionPerformed for a button – ListSelectionListener • Listener interface with only a single method • public void valueChanged(ListSelectionEvent e) • Called whenever the selected item changes – MouseListener • • • • • Has seven methods public void mouseClicked(MouseEvent e) Add this listener to JList Can detect single or double clicks Call getSelectedIndex() to determine which item was clicked 22 Beyond the JOptionPane • JOptionPane was used in CS 1323 to create GUI based interfaces • Very easy to use – One line of code – Don’t necessarily need to use with Event Listeners • Lack some versatility – Has only a single line of input – Must have a long chain of these dialogs for object input • Uses – Short message dialogs – Actions that only need confirmation • Yes/No • OK/Cancel • http://java.sun.com/docs/books/tutorial/uiswin g/components/dialog.html 23 JDialog • Swing component for Dialogs – Used for modal or non-modal dialog windows • Modal dialog: does not allow the user to interact with the rest of the program while dialog is active • Non-Modal dialog: user can interact with program while dialog is active – Construction • Typically, we would write a class that inherits from JDialog • JDialog myDialog = new JDialog (JFrame owner, boolean modal) – The owner frame is the JFrame from which the dialog is shown – Modal can be set either true or false – Many other forms for the JDialog constructor 24 How to design and use Dialogs • This is a confusing topic for many students. PersonEditDialog Controller Pattern dialog person person name email etc..... Person/Student/Professor 25 Dialog Demos • SimpleDialog Demo – StudentDialog.java – StudentEx.java / PersonEx.java • PersonEditDialog Demo – PersonEditDialog.java – Student.java / Professor.java / Person.java • PersonEditDialog with Exception Handling – PersonEditDialogEx.java – StudentEx.java / ProfessorEx.java /PersonEx.java 26