692 Graphical User Interface Components: Part 1 Chapter (Hp web site)

February 17th, 2008

692 Graphical User Interface Components: Part 1 Chapter 12 taining the name of the key that was pressed. For a complete list of virtual key constants, see the on-line documentation for class KeyEvent (package java.awt.event). Method keyTyped(lines 51 55) uses KeyEventmethod getKeyCharto get the Unicode value of the character typed. All three event handling methods finish by calling method setLines2and3 (lines 58 72) and passing it the KeyEvent object. This method uses KeyEvent method isActionKey to determine if the key in the event was an action key. Also, InputEventmethod getModifiersis called to determine if any modifier keys (such as Shift, Alt and Ctrl) were pressed when the key event occurred. The result of this method is passed to KeyEventmethod getKeyModifiersText, which produces a string containing the names of the pressed modifier keys. [Note: If you need to test for a specific key on the keyboard, class KeyEventprovides a key constant for every key on the keyboard. These constants can be used from the key event handlers to determine if a particular key was pressed. Also, to determine whether the Alt, Ctrl, Meta and Shift keys are pressed individually, InputEvent methods isAlt- Down, isControlDown, isMetaDown and isShiftDown each return a boolean indicating if the particular key was pressed during the key event.] 12.14 Layout Managers Layout managers are provided to arrange GUI components on a container for presentation purposes. The layout managers provide basic layout capabilities that are easier to use than determining the exact position and size of every GUI component. This enables the programmer to concentrate on the basic look and feel and lets the layout managers process most of the layout details. Look-and-Feel Observation 12.9 Most Java programming environments provide GUI design tools that help a programmer graphically design a GUI, then automatically write Java code to create the GUI. Some GUI designers also allow the programmer to use the layout managers described here and in Chapter 13. Figure 12.23 summarizes the layout managers presented in this chapter. Other layout managers are discussed in Chapter 13. Layout manager Description FlowLayout Default for java.awt.Applet, java.awt.Paneland javax.swing.JPanel. Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components using the Containermethod addthat takes a Componentand an integer index position as arguments. BorderLayout Default for the content panes of JFrames (and other windows) and JApplets. Arranges the components into five areas: North, South, East, West and Center. GridLayout Arranges the components into rows and columns. Fig. 12.23 Layout managers. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Apache web server for windows - Chapter 12 Graphical User Interface Components: Part 1

February 16th, 2008

Chapter 12 Graphical User Interface Components: Part 1 691 73 74 // execute application 75 public static void main( String args[] ) 76 { 77 KeyDemo application = new KeyDemo(); 78 79 application.setDefaultCloseOperation( 80 JFrame.EXIT_ON_CLOSE ); 81 } 82 83 } // end class KeyDemo Fig. 12.22 Fig. 12.22 Demonstrating key event-handling (part 3 of 3). The constructor (lines 17 32) registers the application to handle its own key events with method addKeyListener at line 28. Method addKeyListener is defined in class Component, so every subclass of Componentcan notify KeyListeners of key events for that Component. Line 25 in the constructor adds JTextAreatextArea(where the program s output is displayed) to the content pane. Notice, in the screen captures, that textAreaoccupies the entire window. This is due to the content pane s default BorderLayout (discussed in Section 12.14.2 and demonstrated in Fig. 12.25). When a single Component is added to a BorderLayout, the Componentoccupies the entire Container. Methods keyPressed (lines 35 40) and keyReleased (lines 43 48) use KeyEventmethod getKeyCodeto get the virtual key code of the key that was pressed. Class KeyEvent maintains a set of constants the virtual key code constants that represent every key on the keyboard. These constants can be compared with the return value of getKeyCodeto test for individual keys on the keyboard. The value returned by get- KeyCodeis passed to KeyEventmethod getKeyText, which returns a Stringcon Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

690 Graphical (Hosting your own web site) User Interface Components: Part 1 Chapter

February 15th, 2008

690 Graphical User Interface Components: Part 1 Chapter 12 20 21 // set up JTextArea 22 textArea = new JTextArea( 10, 15 ); 23 textArea.setText( “Press any key on the keyboard…” ); 24 textArea.setEnabled( false ); 25 getContentPane().add( textArea ); 26 27 // allow frame to process Key events 28 addKeyListener( this ); 29 30 setSize( 350, 100 ); 31 setVisible( true ); 32 } 33 34 // handle press of any key 35 public void keyPressed( KeyEvent event ) 36 { 37 line1 = “Key pressed: ” + 38 event.getKeyText( event.getKeyCode() ); 39 setLines2and3( event ); 40 } 41 42 // handle release of any key 43 public void keyReleased( KeyEvent event ) 44 { 45 line1 = “Key released: ” + 46 event.getKeyText( event.getKeyCode() ); 47 setLines2and3( event ); 48 } 49 50 // handle press of an action key 51 public void keyTyped( KeyEvent event ) 52 { 53 line1 = “Key typed: ” + event.getKeyChar(); 54 setLines2and3( event ); 55 } 56 57 // set second and third lines of output 58 private void setLines2and3( KeyEvent event ) 59 { 60 line2 = “This key is ” + 61 ( event.isActionKey() ? “” : “not ” ) + 62 “an action key”; 63 64 String temp = 65 event.getKeyModifiersText( event.getModifiers() ); 66 67 line3 = “Modifier keys pressed: ” + 68 ( temp.equals( “” ) ? “none” : temp ); 69 70 textArea.setText( 71 line1 + “n” + line2 + “n” + line3 + “n” ); 72 } Fig. 12.22 Fig. 12.22 Demonstrating key event-handling (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 12 (Web server type) Graphical User Interface Components: Part 1

February 15th, 2008

Chapter 12 Graphical User Interface Components: Part 1 689 InputEventmethod Description isMetaDown() This method returns truewhen the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right- mouse-button click on a one-button mouse, the user can press the Meta key on the keyboard and click the mouse button. isAltDown() This method returns truewhen the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle- mouse-button click on a one-or two-button mouse, the user can press the Alt key on the keyboard and click the mouse button. Fig. 12.21 InputEventmethods that help distinguish among left-, center-and right-mouse-button clicks . 12.13 Keyboard Event Handling This section presents the KeyListenerevent-listener interface for handling key events. Key events are generated when keys on the keyboard are pressed and released. A class that implements KeyListener must provide definitions for methods keyPressed, key- Releasedand keyTyped, each of which receives a KeyEventas its argument. Class KeyEvent is a subclass of InputEvent. Method keyPressed is called in response to pressing any key. Method keyTyped is called in response to pressing any key that is not an action key (e.g., an arrow key, Home, End, Page Up, Page Down, a function key, Num Lock, Print Screen, Scroll Lock, Caps Lock and Pause). Method keyReleased is called when the key is released after any keyPressedor keyTypedevent. Figure 12.22 demonstrates the KeyListenermethods. Class KeyDemoimplements the KeyListenerinterface, so all three methods are defined in the application. 1 // Fig. 12.22: KeyDemo.java 2 // Demonstrating keystroke events. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class KeyDemo extends JFrame implements KeyListener { 12 private String line1 = “”, line2 = “”; 13 private String line3 = “”; 14 private JTextArea textArea; 15 16 // set up GUI 17 public KeyDemo() 18 { 19 super( “Demonstrating Keystroke Events” ); Fig. 12.22 Fig. 12.22 Demonstrating key event-handling (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Medical web site - 688 Graphical User Interface Components: Part 1 Chapter

February 14th, 2008

688 Graphical User Interface Components: Part 1 Chapter 12 Fig. 12.20 Fig. 12.20 Distinguishing among left, center and right mouse-button clicks (part 3 of 3). A user of a Java program may be on a system with a one-, two- or three-button mouse. Java provides a mechanism to distinguish among mouse buttons. Class MouseEvent inherits several methods from class InputEventthat can distinguish between mouse buttons on a multi-button mouse or can mimic a multi-button mouse with a combined keystroke and mouse-button click. Figure 12.21 shows the InputEvent methods used to distinguish between mouse-button clicks. Java assumes that every mouse contains a left mouse button. Thus, it is simple to test for a left-mouse-button click. However, users with a one-or two-button mouse must use a combination of pressing keys on the keyboard and clicking the mouse at the same time to simulate the missing buttons on the mouse. In the case of a one-or two-button mouse, this program assumes that the center mouse button is clicked if the user holds the Alt key and clicks the left mouse button on a two-button mouse or the only mouse button on a one-button mouse. In the case of a one-button mouse, this program assumes that the right mouse button is clicked if the user holds the Meta key and clicks the mouse button. Method mouseClicked(lines 51 73) first captures the coordinates where the event occurred and stores them in instance variables xPosand yPosof class MouseDetails. Lines 56 57 create a string containing the number of mouse clicks (as returned by Mouse- Eventmethod getClickCountat line 57). The nested ifstructure at lines 60 69 uses methods isMetaDown and isAltDown to determine which mouse button the user clicked and appends an appropriate string to title in each case. The resulting string is displayed in the title bar of the window with method setTitle (inherited into class JFramefrom class Frame) at line 71. Line 72 calls repaintto initiate a call to paint to draw a string at the location where the user clicked the mouse. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web hosting providers - Chapter 12 Graphical User Interface Components: Part 1

February 13th, 2008

Chapter 12 Graphical User Interface Components: Part 1 687 26 27 // draw String at location where mouse was clicked 28 public void paint( Graphics g ) 29 { 30 // call superclass’s paint method 31 super.paint( g ); 32 33 g.drawString( “Clicked @ [” + xPos + “, ” + yPos + “]”, 34 xPos, yPos ); 35 } 36 37 // execute application 38 public static void main( String args[] ) 39 { 40 MouseDetails application = new MouseDetails(); 41 42 application.setDefaultCloseOperation( 43 JFrame.EXIT_ON_CLOSE ); 44 } 45 46 // inner class to handle mouse events 47 private class MouseClickHandler extends MouseAdapter { 48 49 // handle mouse click event and determine which mouse 50 // button was pressed 51 public void mouseClicked( MouseEvent event ) 52 { 53 xPos = event.getX(); 54 yPos = event.getY(); 55 56 String title = 57 “Clicked ” + event.getClickCount() + ” time(s)”; 58 59 // right mouse button 60 if ( event.isMetaDown() ) 61 title += ” with right mouse button”; 62 63 // middle mouse button 64 else if ( event.isAltDown() ) 65 title += ” with center mouse button”; 66 67 // left mouse button 68 else 69 title += ” with left mouse button”; 70 71 setTitle( title ); // set title bar of window 72 repaint(); 73 } 74 75 } // end private inner class MouseClickHandler 76 77 } // end class MouseDetails Fig. 12.20 Fig. 12.20 Distinguishing among left, center and right mouse-button clicks (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Kids web site - 686 Graphical User Interface Components: Part 1 Chapter

February 13th, 2008

686 Graphical User Interface Components: Part 1 Chapter 12 the default methods do nothing when they are called. So, we override method mouse- Dragged at lines 30 35 to capture the x-and y-coordinates of the mouse-dragged event and store them in instance variables xValueand yValue, then call repaintto initiate drawing the next oval on the background (performed by method paint at lines 47 53). Note that paint does not call the superclass version of paintinherited from JFrame. The superclass version normally clears the background of the window. Not calling the superclass version enables our program to keep all the ovals on the window at once. However, notice that if you cover the window with another window, only the last oval displayed still appears, because our program does not keep track of all the ovals displayed previously. Lines 60 72 register a WindowListener to listen for the application window s window events (such as closing the window). Lines 63 70 define an anonymous inner class that extends class WindowAdapter (which implements WindowListener). The anonymous inner class inherits a default implementation of seven different window-eventhandler methods. Thus, the anonymous inner class already satisfies the requirement that in all methods an interface must be implemented. However, the default methods do nothing when they are called. So, we override method windowClosing at lines 65 68 to terminate the application when the user clicks the application window s close box. The MouseDetails application of Fig. 12.20 demonstrates how to determine the number of mouse clicks (i.e., the click count) and how to distinguish between the different mouse buttons. The event listener in this program is an object of inner class Mouse- ClickHandler (lines 47 75) that extends MouseAdapter so we can define just the mouseClickedmethod we need in this example. 1 // Fig. 12.20: MouseDetails.java 2 // Demonstrating mouse clicks and 3 // distinguishing between mouse buttons. 4 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages import javax.swing.*; 11 12 public class MouseDetails extends JFrame { 13 private int xPos, yPos; 14 // set title bar String, register mouse listener and size 16 // and show window 17 public MouseDetails() 18 { 19 super( “Mouse clicks and buttons” ); 21 addMouseListener( new MouseClickHandler() ); 22 23 setSize( 350, 150 ); 24 setVisible( true ); } Fig. 12.20 Fig. 12.20 Distinguishing among left, center and right mouse-button clicks (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 12 Graphical User (Web site) Interface Components: Part 1

February 12th, 2008

Chapter 12 Graphical User Interface Components: Part 1 685 45 // draw oval in a 4-by-4 bounding box at the specified 46 // location on the window 47 public void paint( Graphics g ) 48 { 49 // we purposely did not call super.paint( g ) here to 50 // prevent repainting 51 52 g.fillOval( xValue, yValue, 4, 4 ); 53 } 54 55 // execute application 56 public static void main( String args[] ) 57 { 58 Painter application = new Painter(); 59 60 application.addWindowListener( 61 62 // adapter to handle only windowClosing event 63 new WindowAdapter() { 64 65 public void windowClosing( WindowEvent event ) 66 { 67 System.exit( 0 ); 68 } 69 70 } // end anonymous inner class 71 72 ); // end call to addWindowListener 73 } 74 75 } // end class Painter Fig. 12.19 Fig. 12.19 Program that demonstrates adapter classes (part 2 of 2). The instance variables xValue and yValue store the coordinates of the mouse- Dragged event. Initially, the coordinates are set outside the window area to prevent an oval from drawing on the background area in the first call to paint when the window is displayed. Lines 24 39 register a MouseMotionListener to listen for the window s mouse motion events (remember that a call to a method that is not preceded by a reference and a dot operator is really preceded by this. , indicating that the method is called for the current instance of the class at execution time). Lines 27 37 define an anonymous inner class that extends class MouseMotionAdapter (which implements MouseMotion- Listener). The anonymous inner class inherits a default implementation of both method mouseMoved and method mouseDragged. Thus, the anonymous inner class already satisfies the requirement that in all methods an interface must be implemented. However, Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

684 Graphical User Interface Components: Part 1 (Free web host) Chapter

February 11th, 2008

684 Graphical User Interface Components: Part 1 Chapter 12 The Painter application of Fig. 12.19 uses the mouseDragged event handler to create a simple drawing program. The user can draw pictures with the mouse by dragging the mouse on the background of the window. This example does not use method mouse- Moved, so our MouseMotionListener is defined as a subclass of Mouse- MotionAdapter. This class already defines both mouseMovedand mouseDragged, so we can simply override mouseDraggedto provide the drawing functionality. 1 // Fig. 12.19: Painter.java 2 // Using class MouseMotionAdapter. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class Painter extends JFrame { 12 private int xValue = -10, yValue = -10; 13 14 // set up GUI and register mouse event handler 15 public Painter() 16 { 17 super( “A simple paint program” ); 18 19 // create a label and place it in SOUTH of BorderLayout 20 getContentPane().add( 21 new Label( “Drag the mouse to draw” ), 22 BorderLayout.SOUTH ); 23 24 addMouseMotionListener( 25 26 // anonymous inner class 27 new MouseMotionAdapter() { 28 29 // store drag coordinates and repaint 30 public void mouseDragged( MouseEvent event ) 31 { 32 xValue = event.getX(); 33 yValue = event.getY(); 34 repaint(); 35 } 36 37 } // end anonymous inner class 38 39 ); // end call to addMouseMotionListener 40 41 setSize( 300, 150 ); 42 setVisible( true ); 43 } 44 Fig. 12.19 Fig. 12.19 Program that demonstrates adapter classes (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Linux web host - Chapter 12 Graphical User Interface Components: Part 1

February 11th, 2008

Chapter 12 Graphical User Interface Components: Part 1 683 When any of the other five events occur, they display a message in statusBarthat includes a String that represents the event that occurred and the coordinates where the mouse event occurred. The x and y coordinates of the mouse when the event occurred are obtained with MouseEventmethods getXand getY, respectively. 12.12 Adapter Classes Many of the event-listener interfaces provide multiple methods; MouseListener and MouseMotionListenerare examples. It is not always desirable to define every method in an event-listener interface. For example, a program may only need the mouse- Clicked handler from interface MouseListener or the mouseDragged handler from MouseMotionListener. In our windowed applications (subclasses of JFrame) terminating the application has been handled with windowClosingfrom interface WindowListener, which actually specifies seven window-event-handling methods. For many of the listener interfaces that contain multiple methods, package java.awt.event and package javax.swing.event provide event-listener adapter classes. An adapter class implements an interface and provides a default implementation (with an empty method body) of every method in the interface. The java.awt.event adapter classes are shown in Fig. 12.18 along with the interfaces they implement. The programmer can extend the adapter class to inherit the default implementation of every method, then override the method(s) needed for event handling. The default implementation of each method in the adapter class has an empty body. This is exactly what we have been doing in each application example that extends JFrame and defines method windowClosingto handle the closing of the window and termination of the application. Software Engineering Observation 12.3 When a class implements an interface, the class has an is a relationship with that interface. All direct and indirect subclasses of that class inherit this relationship. Thus, an object of a class that extends an event adapter class is an object of the corresponding event listener type (e.g., an object of a subclass of MouseAdapteris a MouseListener). Event adapter class Implements interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener Fig. 12.18Event adapter classes and the interfaces they implement. 12.18 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01