Ivor Horton’s Beginning Java 2, JDK 5 Edition phần 7 ppt

150 341 0
Ivor Horton’s Beginning Java 2, JDK 5 Edition phần 7 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

// Handle window events protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { dispose(); // Release resources System.exit(0); // Exit the program } super.processWindowEvent(e); // Pass on the event } private JMenuBar menuBar = new JMenuBar(); // Window menu bar // File menu items private JMenuItem newItem, openItem, closeItem, saveItem, saveAsItem, printItem; // Element menu items private JRadioButtonMenuItem lineItem, rectangleItem, circleItem, // Types curveItem, textItem; private JCheckBoxMenuItem redItem, yellowItem, // Colors greenItem, blueItem ; } You add the call to enableEvents() as the last in the constructor. Note that the statement that sets EXIT_ON_CLOSE as the close option for the window is commented out. You could delete the statement if you want. When you compile SketchFrame and run Sketcher again, you’ll be able to close the window as before, and the program will shut down gracefully. However, this time it’s your method that’s doing it. How It Works The additional import statements make the constants defined in the AWTEvent class and the WindowEvent class name available to your source file without the need to qualify them with the package names. You call enableEvents() in the constructor with WINDOW_EVENT_MASK as the argu- ment to enable window events. This enables all the window events represented by the WindowEvent class. An object of this class can represent one of a number of different window events that are each iden- tified by an event ID, which is a constant defined within the WindowEvent class. The event IDs for the WindowEvent class are: Event ID Description WINDOW_OPENED The event that occurs the first time a window is made visible. WINDOW_CLOSING The event that occurs as a result of the close icon being selected or Close being selected from the window’s system menu. WINDOW_CLOSED The event that occurs when the window has been closed. WINDOW_ACTIVATED The event that occurs when the window is activated — obtains the focus, in other words. When another GUI component has the focus, you could make the window obtain the focus by clicking on it, for example. Table continued on following page 871 Handling Events 21_568744 ch18.qxd 11/23/04 9:40 PM Page 871 Event ID Description WINDOW_DEACTIVATED The event that occurs when the window is deactivated — loses the focus, in other words. Clicking on another window would cause this event, for example. WINDOW_GAINED_FOCUS The event that occurs when the window gains the focus. This implies that the window or one of its components will receive keyboard events. WINDOW_LOST_FOCUS The event that occurs when the window loses the focus. This implies that keyboard events will not be delivered to the window or any of its components. WINDOW_ICONIFIED The event that occurs when the window is minimized and reduced to an icon. WINDOW_DEICONIFIED The event that occurs when the window is restored from an icon. WINDOW_STATE_CHANGED The event that occurs when the window state changes — when it is maximized or minimized, for instance. If any of these events occur, the processWindowEvent() method that you have added to the SketchFrame class will be called. Your version of the method overrides the base class method that is inherited from java.awt.Window, and is responsible for passing the event to any listeners that have been registered. The argument of type WindowEvent that is passed to the method will contain the event ID that identifies the particular event that occurred. To obtain the ID of the event, you call the getID() method for the event object, and compare that with the ID identifying the WINDOW_CLOSING event. If the event is WINDOW_CLOSING, you call the dispose() method for the window to close the window and release the system resources it is using. You then close the application by calling the exit() method defined in the System class. The getID() method is defined in the AWTEvent class, which is a superclass of all the low-level event classes I have discussed, so all event objects that encapsulate low-level events have this method. In the SketchFrame class, the dispose() method is inherited originally from the Window class via the base class JFrame. This method releases all the resources for the window object, including those for all components owned by the object. Calling the dispose() method doesn’t affect the window object itself in the program. It just tells the operating system that the resources used to display the window and the components it contains on the screen are no longer required. The window object is still around together with its components, so you could call its methods or even open it again. Note that you call the processWindowEvent() method in the superclass if it is not the closing event. It is very important that you do this as it allows the event to be passed on to any listeners that have been registered for these events. If you don’t call processWindowEvent() for the superclass, any events that you do not handle in your processWindowEvent() method will be lost, because the base class method is normally responsible for passing the event to the listeners that have been registered to receive it. 872 Chapter 18 21_568744 ch18.qxd 11/23/04 9:40 PM Page 872 If you had not commented out the call to the setDefaultCloseOperation() method, your processWindowEvent() method would still have been called when the close icon was clicked. In this case you would not need to call dispose() and exit() in the method. This would all have been taken care of automatically after your processWindowEvent() method had finished executing. This would be preferable as it means there would be less code in your program, and the code to handle the default close action is there in the JFrame class anyway. Enabling Other Low-level Events The enableEvents() method is inherited from the Component class. This means that any component can elect to handle its own events. You just call the enableEvents() method for the component and pass an argument defining the events you want the component to handle. If you want to enable more than one type of event for a component, you just combine the event masks from AWTEvent that you saw earlier by linking them with a bitwise OR. To make the window object handle mouse events as well as window events, you could write: enableEvents(WINDOW_EVENT_MASK | MOUSE_EVENT_MASK); Of course, you must now also implement the processMouseEvent() method for the SketchFrame class. Like the processWindowEvent() method, this method is protected and has void as the return type. It receives the event as an argument of type MouseEvent. There are two other methods specific to the Window class that handle events: Event-Handling Methods Description processWindowFocusEvent(WindowEvent e) This method is called for any window focus events that arise as long as such events are enabled for the window. processWindowStateEvent(WindowEvent e) This method is called for events arising as a result of the window changing state. These methods and the processWindowEvent() method are available only for objects of type Window or of a type that is a subclass of Window, so don’t try to enable window events on other components. The other event-handling methods that you can override to handle component events are: Event-Handling Methods Description processEvent(AWTEvent e) This method is called first for any events that are enabled for the component. If you implement this method and fail to call the base class method, none of the methods for specific groups of events will be called. processFocusEvent(FocusEvent e) This method will be called for focus events, if they are enabled for the component. Table continued on following page 873 Handling Events 21_568744 ch18.qxd 11/23/04 9:40 PM Page 873 Event-Handling Methods Description processKeyEvent(KeyEvent e) This method will be called for key events, if they are enabled for the component. processMouseEvent(MouseEvent e) This method will be called for mouse button events, if they are enabled for the component. processMouseMotionEvent(MouseEvent e) This method will be called for mouse move and drag events, if they are enabled for the component. processMouseWheelEvent(MouseWheelEvent e) This method will be called for mouse wheel rotation events, if they are enabled for the component. All the event-handling methods for a component are protected methods that have a return type of void. The default behavior implemented by these methods is to dispatch the events to any listeners registered for the component. If you don’t call the base class method when you override these methods after your code has executed, this behavior will be lost. Low-Level Event Listeners To create a class that defines an event listener, your class must implement a listener interface. All event lis- tener interfaces extend the interface java.util.EventListener. This interface doesn’t declare any methods, though — it’s just used to identify an interface as being an event listener interface. It also allows a variable of type EventListener to be used for storing a reference to any kind of event listener object. There is a very large number of event listener interfaces. You’ll consider just eight at this point that are concerned with low-level events. The following sections describe these interfaces and the methods they declare. Although it seemed to be convenient to handle the window-closing event in the SketchFrame class by implementing processWindowEvent(), as a general rule you should use listeners to handle events. Using listeners is the recommended approach to handling events in the majority of circumstances, since separating the event handling from the object that originated the event results in a simpler code structure that is eas- ier to understand and is less error prone. You will change the handling of the window- closing event in the Sketcher code to use a listener a little later in this chapter. 874 Chapter 18 21_568744 ch18.qxd 11/23/04 9:40 PM Page 874 The WindowListener Interface This interface defines methods to respond to events reflecting changes in the state of a window. Defined Methods Description windowOpened(WindowEvent e) Called the first time the window is opened windowClosing(WindowEvent e) Called when the system menu Close item or the window close icon is selected windowClosed(WindowEvent e) Called when the window has been closed windowActivated(WindowEvent e) Called when the window is activated — by clicking on it, for example windowDeactivated(WindowEvent e) Called when a window is deactivated — by click- ing on another window, for example windowIconified(WindowEvent e) Called when a window is minimized and reduced to an icon windowDeiconified(WindowEvent e) Called when a window is restored from an icon The WindowFocusListener Interface This interface defines methods to respond to a window gaining or losing the focus. When a window has the focus, one of its child components can receive input from the keyboard. When it loses the focus, key- board input via a child component of the window is not possible. Defined Methods Description windowGainedFocus(WindowEvent e) Called when the window gains the focus such that the window or one of its components will receive keyboard events. windowLostFocus(WindowEvent e) Called when the window loses the focus. After this event, neither the window nor any of its compo- nents will receive keyboard events. The WindowStateListener Interface This interface defines a method to respond to any change in the state of a window. Defined Method Description windowStateChanged(WindowEvent e) Called when the window state changes — when it is maximized or iconified, for example 875 Handling Events 21_568744 ch18.qxd 11/23/04 9:40 PM Page 875 The MouseListener Interface This interface defines methods to respond to events arising when the mouse cursor is moved into or out of the area occupied by a component, or one of the mouse buttons is pressed, released, or clicked. Defined Methods Description mouseClicked(MouseEvent e) Called when a mouse button is clicked on a component— that is, when the button is pressed and released mousePressed(MouseEvent e) Called when a mouse button is pressed on a component mouseReleased(MouseEvent e) Called when a mouse button is released on a component mouseEntered(MouseEvent e) Called when the mouse enters the area occupied by a component mouseExited(MouseEvent e) Called when the mouse exits the area occupied by a component The MouseMotionListener Interface This interface defines methods that are called when the mouse is moved or dragged with a button pressed. Defined Methods Description mouseMoved(MouseEvent e) Called when the mouse is moved within a component mouseDragged(MouseEvent e) Called when the mouse is moved within a component while a mouse button is held down The MouseWheelListener Interface This interface defines a method to respond to the mouse wheel being rotated. This is frequently used to scroll information that is displayed, but you can use it in any way that you want. Defined Method Description mouseWheelMoved(MouseWheelEvent e) Called when the mouse wheel is rotated The KeyListener Interface This interface defines methods to respond to events arising when a key on the keyboard is pressed or released. 876 Chapter 18 21_568744 ch18.qxd 11/23/04 9:40 PM Page 876 Defined Methods Description keyTyped(KeyEvent e) Called when a key on the keyboard is pressed and then released keyPressed(KeyEvent e) Called when a key on the keyboard is pressed keyReleased(KeyEvent e) Called when a key on the keyboard is released The FocusListener Interface This interface defines methods to respond to a component gaining or losing the focus. You might imple- ment these methods to change the appearance of the component to reflect whether or not it has the focus. Defined Methods Description focusGained(FocusEvent e) Called when a component gains the keyboard focus focusLost(FocusEvent e) Called when a component loses the keyboard focus There is a further listener interface, MouseInputListener, that is defined in the javax.swing.event package. This listener implements both the MouseListener and MouseMotionListener interfaces so it declares methods for all possible mouse events in a single interface. The WindowListener, WindowFocusListener, and WindowStateListener interfaces define methods corresponding to each of the event IDs defined in the WindowEvent class that you saw earlier. If you deduced from this that the methods in the other listener interfaces correspond to event IDs for the other event classes, well, you’re right. All the IDs for mouse events are defined in the MouseEvent class. These are: MOUSE_CLICKED MOUSE_PRESSED MOUSE_DRAGGED MOUSE_ENTERED MOUSE_EXITED MOUSE_RELEASED MOUSE_MOVED MOUSE_WHEEL The MOUSE_MOVED event corresponds to just moving the mouse. The MOUSE_DRAGGED event arises when you move the mouse while keeping a button pressed. The event IDs that the KeyEvent class defines are: KEY_TYPED KEY_PRESSED KEY_RELEASED Those defined in the FocusEvent class are: FOCUS_GAINED FOCUS_LOST 877 Handling Events 21_568744 ch18.qxd 11/23/04 9:40 PM Page 877 public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} private SketchFrame window; // The application window private static Sketcher theApp; // The application object } If you run the Sketcher program again, you will see it works just as before, but now the Sketcher class object is handling the close operation. How It Works You have added import statements for the WindowEvent and WindowListener class names. The Sketcher class now implements the WindowListener interface, so an object of type Sketcher can handle window events. The main() method now creates a Sketcher object and stores the reference in the static class member theApp. The createGUI() method is now an instance method, and this executes on the event-dispatching thread as shown in the previous example. The createGUI() method creates the application window object as before, but now the reference is stored in a field belonging to theApp. After setting up the win- dow components, the createGUI() method calls the addWindowListener() method for the window object. The argument to the addWindowListener() method is a reference to the listener object that is to receive window events. Here it is the variable this, which refers to the application object, theApp. If you had other listener objects that you wanted to register to receive this event, you would just need to add more calls to the addWindowListener() method — one call for each listener. When you implement the WindowListener interface in the Sketcher class, you must implement all seven methods that are declared in the interface. If you failed to do this, the class would be abstract and you could not create an object of type Sketcher. Only the windowClosing() method contains code here— the bodies of all the other methods are empty because you don’t need to use them. The windowClosing() method does the same as the processWindowEvent() method that you implemented for the previous version of the SketchFrame class, but here you don’t need to check the object passed to it because the windowClosing() method is called only for a WINDOW_CLOSING event. You don’t need to pass the event on either; this is necessary only when you handle events in the manner I discussed earlier. Here, if there were other listeners around for the window events, they would automatically receive the event. You have included the code that calls dispose() and exit() here, but if you set the default close oper- ation in SketchFrame to EXIT_ON_CLOSE, you could omit these, too. You really need to put your appli- cation cleanup code only in the windowClosing() method, and this will typically display a dialog to just prompt the user to save any application data. You will get to that eventually. Having to implement six methods that you don’t need is rather tedious. But you have a way to get around this — by using what is called an adapter class, to define a listener. Using Adapter Classes An adapter class is a term for a class that implements a listener interface with methods that have no con- tent, so they do nothing. The idea of this is to enable you to derive your own listener class from any of the 879 Handling Events 21_568744 ch18.qxd 11/23/04 9:40 PM Page 879 To implement a listener for a particular event type, you just need to implement the methods declared in the corresponding interface. You could handle some of the window events for the SketchFrame class by making the application class the listener for window events. Try It Out Implementing a Low-Level Event Listener First, delete the call to the enableEvents() method in the SketchFrame() constructor. Then delete the definition of the processWindowEvent() method from the class definition. Now you can modify the previous version of the Sketcher class so that it is a listener for window events: // Sketching application import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowListener; import java.awt.event.WindowEvent; public class Sketcher implements WindowListener { public static void main(String[] args) { theApp = new Sketcher(); // Create the application object SwingUtilities.invokeLater( new Runnable() { // Anonymous Runnable class object public void run() { // Run method executed in thread theApp.creatGUI(); // Call static GUI creator } } ); } // Method to create the application GUI private void creatGUI() { window = new SketchFrame(“Sketcher”); // Create the app window Toolkit theKit = window.getToolkit(); // Get the window toolkit Dimension wndSize = theKit.getScreenSize(); // Get screen size // Set the position to screen center & size to half screen size window.setBounds(wndSize.width/4, wndSize.height/4, // Position wndSize.width/2, wndSize.height/2); // Size window.addWindowListener(this); // theApp as window listener window.setVisible(true); } // Handler for window closing event public void windowClosing(WindowEvent e) { window.dispose(); // Release the window resources System.exit(0); // End the application } // Listener interface functions you must implement – but don’t need public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} 878 Chapter 18 21_568744 ch18.qxd 11/23/04 9:40 PM Page 878 adapter classes that are provided, and then implement just the methods that you are interested in. The other empty methods will be inherited from the adapter class so you don’t have to worry about them. There’s an adapter class defined in the javax.swing.event package that defines the methods for the MouseInputListener interface. There are five further adapter classes defined in the java.awt.event package that cover the methods in the other low-level listener interfaces you have seen: FocusAdapter WindowAdapter KeyAdapter MouseAdapter MouseMotionAdapter MouseInputAdapter The WindowAdapter class implements all of the methods defined in the WindowListener, WindowFocusListener, and WindowStateListener interfaces. The other five each implement the methods in the corresponding listener interface. To handle the window closing event for the Sketcher application, you could derive your own class from the WindowAdapter class and just implement the windowClosing() method. If you also make it an inner class for the Sketcher class, it will automatically have access to the members of the Sketcher object, regardless of their access specifiers. Let’s change the structure of the Sketcher class once more to make use of an adapter class. Try It Out Implementing an Adapter Class The version of the Sketcher class to implement this will be as follows, with changes to the previous version highlighted: // Sketching application import java.awt.Toolkit; import java.awt.Dimension; import javax.swing.SwingUtilities; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; public class Sketcher { public static void main(String[] args) { theApp = new Sketcher(); // Create the application object SwingUtilities.invokeLater( new Runnable() { // Anonymous Runnable class object public void run() { // Run method executed in thread theApp.creatGUI(); // Call static GUI creator } } ); } // Method to create the application GUI private void creatGUI() { window = new SketchFrame(“Sketcher”); // Create the app window Toolkit theKit = window.getToolkit(); // Get the window toolkit Dimension wndSize = theKit.getScreenSize(); // Get screen size 880 Chapter 18 21_568744 ch18.qxd 11/23/04 9:40 PM Page 880 [...]... import import import import import import import javax.swing.JFrame; javax.swing.JMenuBar; javax.swing.JMenu; javax.swing.JMenuItem; javax.swing.JRadioButtonMenuItem; javax.swing.JCheckBoxMenuItem; javax.swing.ButtonGroup; javax.swing.KeyStroke; static java. awt.event.InputEvent.*; static java. awt.AWTEvent.*; java. awt.event.WindowEvent; java. awt.Color; static java. awt.Color.*; static Constants.SketcherConstants.*;... application import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.JCheckBoxMenuItem; import javax.swing.ButtonGroup; import javax.swing.KeyStroke; import javax.swing.Action; import javax.swing.AbstractAction; import java. awt.event.WindowEvent; import java. awt.event.ActionListener; import java. awt.event.ActionEvent; import java. awt.Color; import... change the button color Figure 18 -5 shows how the applet will look when running under appletviewer: Figure 18 -5 Try It Out A Lottery Applet You can outline the broad structure of the applet’s code as follows: // Applet to generate lottery entries import javax.swing.JButton; import javax.swing.JApplet; import javax.swing.JPanel; import javax.swing.BorderFactory; import javax.swing.SwingUtilities; import... import javax.swing.JApplet; import javax.swing.JPanel; import javax.swing.BorderFactory; import javax.swing.SwingUtilities; import import import import import 884 java. awt.GridLayout; java. awt.FlowLayout; java. awt.Dimension; java. awt.Container; java. awt.Color; Chapter 18 // An array of custom buttons for the selected numbers private Selection[] luckyNumbers = new Selection[numberCount]; private static... directory is the one containing Sketcher .java and SketchFrame .java, you will need to use the following command to compile Sketcher: javac -classpath “.;C:/Packages” Sketcher .java The -classpath option defines two paths: the current directory, specified by the period, and C:/Packages, which is the path to the Constants directory that contains the SketcherConstants .java source file This command should compile... import java. awt.Cursor; import java. awt.event.MouseEvent; import java. awt.event.MouseAdapter; class MouseHandler extends MouseAdapter { Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); // Handle mouse entering the selection button public void mouseEntered(MouseEvent e) { e.getComponent().setCursor(handCursor); // Switch to hand cursor } 8 95 Chapter... are derived from the AWTEvent class, as shown in Figure 18-4 In package java. util EventObject In package java. awt AWTEvent ActionEvent The base class for all semantic events There are semantic events specific to Swing components derived directly from this class ItemEvent AdjustmentEvent These three sematic event classes are in java. awt.event Figure 18-4 An ActionEvent is generated when you perform... a simple applet now, and then see how you can deal with semantic events in a more complicated context by adding to the Sketcher program later 883 Handling Events import java. util.Random; import java. awt.event.ActionListener; import java. awt.event.ActionEvent; // For random number generator public class Lottery extends JApplet { // Initialize the applet public void init() { // Create interface components... java. awt.event.WindowEvent; import java. awt.event.ActionListener; import java. awt.event.ActionEvent; import java. awt.Color; import import import import static static static static java. awt.event.InputEvent.*; java. awt.AWTEvent.*; java. awt.Color.*; Constants.SketcherConstants.*; public class SketchFrame extends JFrame { // Constructor public SketchFrame(String title) { setTitle(title); setJMenuBar(menuBar);... to be used as a tooltip ❑ An accelerator key for the action — Defined by a javax.swing.KeyStroke object ❑ A long description of the action — A String object that is intended to be used as contextsensitive help ❑ A mnemonic key for the action — This is a key code of type int ❑ An action command key — Defined by an entry in a javax.swing.ActionMap object associated with a component The ActionMap object . entries import javax.swing.JButton; import javax.swing.JApplet; import javax.swing.JPanel; import javax.swing.BorderFactory; import javax.swing.SwingUtilities; import java. awt.GridLayout; import java. awt.FlowLayout; import. KEY_RELEASED Those defined in the FocusEvent class are: FOCUS_GAINED FOCUS_LOST 877 Handling Events 21 _56 874 4 ch18.qxd 11/23/04 9:40 PM Page 877 public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent. state changes — when it is maximized or iconified, for example 8 75 Handling Events 21 _56 874 4 ch18.qxd 11/23/04 9:40 PM Page 8 75 The MouseListener Interface This interface defines methods to respond

Ngày đăng: 13/08/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan