GUI Event Handlers (Part II) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1
Agenda Listener Interfaces and Event Classes How to Handle Combo Box Events How to Write a List Selection Listener How to Write a Key Listener How to Write a Mouse Listener Advanced Swing Components JSlider, JColorChooser, JFileChooser How to Write a Change Listener 2
ActionListener & ActionEvent interface ActionListener { // Invoked when an action occurs. void actionperformed(actionevent e); } Important methods of ActionEvent String getactioncommand(): Returns the command string associated with this action long getwhen(): Returns the timestamp of when this event occurred. 3
ItemListener & ItemEvent interface ItemListener { // Invoked when an item has been selected or deselected void itemstatechanged(itemevent e); } Important methods of ItemEvent Object getitem(): Returns the item affected by the event int getstatechange(): Returns the type of state change (selected or deselected) ItemEvent.SELECTED ItemEvent.DESELECTED 4
ComponentListener interface ComponentListener { // Invoked when the component has been made invisible. void componenthidden(componentevent e) // Invoked when the component's position changes. void componentmoved(componentevent e) // Invoked when the component's size changes. void componentresized(componentevent e) // Invoked when the component has been made visible. void } componentshown(componentevent e) 5
ComponentEvent Class Component getcomponent() Returns the originator of the event Important methods of Component void requestfocus(); void repaint(); int getwidth(); int getheight(); int getx(); int gety(); 6
How to Handle Combo Box Events Define a listener class that implements ActionListener Perform type casting from ActionEvent to JComboBox Implement handling method public void actionperformed(actionevent e) {...} JComboBox cb = (JComboBox)e.getSource(); Use getselecteditem to find out which item is selected String selecteditem = (String)cb.getSelectedItem(); 7
ComboBoxDemo (1/2) 8
ComboBoxDemo (2/2) 9
How to Write a List Selection Listener List selection events occur when the selection in a list or table is either changing or has just changed List selection events are fired from an object that implements the ListSelectionModel interface To get a table's list selection model object, you can use either getselectionmodel method or getcolumnmodel().getselectionmodel(). 10
Detecting Selection To detect list selection events, you register a listener on the list selection model object The JList class also gives you the option of registering a listener on the list itself, rather than directly on the list selection model Selection mode single selection mode single interval selection mode multiple interval selection mode 11
ListSelectionModel This interface represents the current state of the selection for any of the components that display a list of values with stable indices The selection is modeled as a set of intervals, each interval represents a contiguous range of selected list elements. The isadjusting flag is true if the user is still manipulating the selection, and false if the user has finished changing the selection. 12
ListSelectionModel & ListSelectionInterface ListSelectionModel addlistselectionlistener(listselectionlistener x) Add a listener to the list that's notified each time a change to the selection occurs. interface ListSelectionListener { // Called whenever the value of the selection changes. public void valuechanged(listselectionevent e); } 13
ListSelectionEvent Important methods of ListSelectionEvent class int getfirstindex(); int getlastindex(); Returns the index of the first row whose selection may have changed. boolean Returns the index of the last row whose selection may have changed. getvalueisadjusting(); Returns whether or not this is one in a series of multiple events, where changes are still being made. 14
JListDemoV2 15
JListDemoV3 (1/4) 16
JListDemoV3 (2/4) 17
JListDemoV3 (3/4) 18
JListDemoV3 (4/4) 19
JListDemoV3 Output 20
Key Events Key events indicate when the user is typing at the keyboard Specifically, key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys Notifications are sent about two basic kinds of key events: The typing of a Unicode character (key typed) The pressing or releasing of a key on the keyboard 21 (key pressed or key released)
Firing Keyboard Events To fire keyboard events, a component must have the keyboard focus Make sure the component's isfocusable method returns true setfocusable(true) method on the component. Make sure the component requests the focus when appropriate For custom components, implement a mouse listener that calls the requestfocusinwindow method when the component is clicked. 22
KeyListener void Invoked when a key has been pressed. void keyreleased(keyevent e) Invoked when a key has been released. void keypressed(keyevent e) keytyped(keyevent e) Invoked when a key has been typed. 23
KeyEvent int getkeycode() Returns the integer keycode associated with the key in this event or VK_UNDEFINED (for a key typed event) char getkeychar() Returns the character associated with the key in this event For example, the KEY_TYPED event for shift + "a" returns the value for "A" 24
KeyEventDemo Example It consists of a text field that you can type into, followed by a text area that displays a message every time the text field fires a key event Type a lowercase 'a' by pressing and releasing the A key on the keyboard The text field fires three events: a key pressed event, a key typed event, and a key released event Type an uppercase 'A' by pressing the Shift and A keys. You'll see the following events, although perhaps not in this order: key pressed (Shift), key pressed (A), key typed ('A'), key 25 released (A), key released (Shift)
KeyEventDemo (1/4) 26
KeyEventDemo (2/4) 27
KeyEventDemo (3/4) 28
KeyEventDemo (4/4) 29
Mouse Events Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons Tracking the cursor's motion involves significantly more system overhead than tracking other mouse events That is why mouse motion events are separated into Mouse Motion listener type To track mouse wheel events, you can register 30 a mouse wheel listener
MouseListener Interface void Invoked when the mouse enters a component. Invoked when the mouse exits a component. void mousepressed(mouseevent e) mouseentered(mouseevent e) void mouseexited(mouseevent e) Invoked when the mouse button has been clicked (pressed and released) on a component void mouseclicked(mouseevent e) Invoked when a mouse button has been pressed on a component. void mousereleased(mouseevent e) Invoked when a mouse button has been released on a component. 31
MouseEvent int Returns the horizontal x position of the event relative to the source component int gety() getx() int Returns the vertical y position of the event relative to the source component. getclickcount() Returns the number of mouse clicks associated with this event. 32
MouseEventDemo (1/3) 33
MouseEventDemo (2/3) 34
MouseEventDemo (3/3) 35
JSlider A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value By default, spacing for major and minor tick marks is zero To see tick marks, set the spacing for either major or minor tick marks (or both) to a non zero value and call the setpaintticks(true) method. To display standard, numeric labels at major tick mark locations, set the major tick spacing, then call the 36 setpaintlabels(true) method
JSlider Examples The second slider is decorated with ticks The third one is decorated with labels It s possible for a single slider to have both types of decorations 37
JSlider Constructors public JSlider(int minimum, int maximum, int value) The most commonly used constructor The first and second parameters are the start and end of the range of values for the slider The third parameter is its initial value when it first appears on the screen If the parameters are omitted, the values 0, 100, and 50 are used 38
JSlider Important Methods By default, a slider is horizontal, but you can make it vertical by calling its method setorientation(jslider.vertical) The current value of a JSlider can be read at any time with its getvalue() method, which returns a value of type int If you want to change the value, you can do so with the method setvalue(n), which takes a parameter of type int 39
JSliderDemo 40
JSliderDemoV2 41
ChangeListener When you move the slider's knob, the statechanged method of the slider's ChangeListener is called ChangeListener is in package javax.swing.event Several Swing components rely on change events for basic functionality sliders, color choosers and spinners 42
ChangeListener & ChangeEvent interface ChangeListener { // Called when the listened to component changes state. void statechanged(changeevent) } Important methods of ChangeEvent int getvalue(): To get the value of the slider String getname(): To get the name of the slider void setname(string s): To set the name of the slider 43
JSliderDemoV3 44
Dialogs A Dialog window is an independent subwindow meant to carry temporary notice apart from the main Swing Application Window Most Dialogs present an error message or warning to a user Dialogs can present images, directory trees, or just about anything compatible with the main Swing Application that manages them 45
Classes for Creating Dialogs To create simple, standard dialogs, you use the JOptionPane class The ProgressMonitor class can put up a dialog that shows the progress of an operation Two other classes, JColorChooser and JFileChooser, also supply standard dialogs To create a custom dialog, use the JDialog class directly 46
JDialog Class The JDialog class is very similar to JFrame and is used in much the same way Like a frame, a dialog box is a separate window Unlike a frame, however, a dialog is not completely independent Every dialog is associated with a frame (or another dialog), which is called its parent window If the parent is closed, the dialog box will also be47 closed
Modal or Modeless Dialog boxes can be either modal or modeless When a modal dialog is created, its parent frame is blocked The user will not be able to interact with the parent until the dialog box is closed In practice, modal dialog boxes are easier to use and are much more common than modeless dialogs 48
JColorChooser JColorChooser is a subclass of JDialog Use the JColorChooser class to provide users with a palette of colors to choose from A color chooser is a component that you can place anywhere within your program GUI The JColorChooser API also makes it easy to bring up a dialog (modal or not) that contains a color chooser. 49
ColorChooserDemo (1/2) 50
ColorChooserDemo (2/2) 51
ColorChooserDemo Output 52
ColorChooserDemoV2 Set both background and foreground colors 53
FileChooser File choosers provide a GUI for navigating the file system Choosing a file or directory from a list Entering the name of a file or directory To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser Another way to present a file chooser is to add an instance of JFileChooser to a container 54
JFileChooser A JFileChooser is a dialog to select a file or files The return value of the three methods is one of the following: 1. JFileChooser.CANCEL_OPTION, if the user clicks Cancel 2. JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button. 3. JFileChooser.ERROR_OPTION, if the user closes the dialog 55
Getting the Chosen File To get the chosen file, call the getselectedfile method on the file chooser The method getselectedfile returns an instance of File You can call other methods on the File object, such as getpath, isdirectory, or exists to obtain information about the file You can also call other methods such as delete and rename to change the file in some way. 56
FileChooserDemo (1/3) 57
FileChooserDemo (2/3) 58
FileChooserDemo (3/3) 59
FileChooserDemo Output 60
References David J. Eck, Introduction to Programming Using Java, Version 5.0, December 2006 http://math.hws.edu/javanotes/ Sun, Writing Event Listeners, http://java.sun.com/docs/books/tutorial/uiswing/even Sun, Using Swing Components, http://java.sun.com/docs/books/tutorial/uiswing/com 61