Chapter 7 EventDriven Programming and Basic GUI Objects

Chapter 7 Event-Driven Programming and Basic GUI Objects ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 7 Objectives After you have read and studied this chapter, you should be able to • Define a subclass of the JFrame class, using inheritance. • Write graphical user interface (GUI) application programs using JButton, JLabel, Image. Icon, JText. Field, and JText. Area objects from the javax. swing package. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 7 Objectives After you have read and studied this chapter, you should be able to • Write GUI application programs with menus, using menu objects from the javax. swing package. • Write event-driven programs, using Java’s delegation-based event model. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Introduction This chapter covers the graphical user interface (GUI). In Java, GUI-based programs are implemented by using classes from the javax. swing and java. awt packages. The Swing classes provide greater compatibility across different operating systems. They are fully implemented in Java, and behave the same on different operating systems. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 1 Various GUI objects from the javax. swing package. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Introduction AWT classes are implemented by using the native GUI objects. Swing classes support many new functionalities not supported by AWT counterparts. Do not mix the counterparts in the same program because of their differences in implementation. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Introduction To build an effective GUI using objects from the Swing and AWT packages, we must learn a new style of program control called event-driven programming. An event occurs when the user interacts with a GUI object. In event-driven programs, we program objects to respond to these events by defining event-handling methods. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame As we know from Chapter 1, inheritance is a feature we use to define a more specialized class from an existing class. The existing class is the superclass and the specialized class is the subclass. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 2 The inheritance hierarchy of JOption. Pane as shown in the API documentation. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame To create a customized user interface, we often define a subclass of the JFrame class. The JFrame class contains rudimentary functionalities to support features found in any frame window. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame /* Chapter 7 Sample Program: Displays a default JFrame window File: Ch 7 Default. JFrame. java */ import javax. swing. *; class Ch 7 Default. JFrame { public static void main( String[] args ) { JFrame default. JFrame; default. JFrame = new JFrame(); default. JFrame. set. Visible(true); } } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 3 A default JFrame window appears at the top left corner of the screen. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame To define a subclass of another class, we declare the subclass with the reserved word extends. class Ch 7 JFrame. Subclass 1 extends JFrame {. . . } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame We will also add the following default characteristics: • The title is set to My First Subclass. • The program terminates when the close box is clicked. • The size of the frame is 300 pixels wide by 200 pixels high. • The frame is positioned at screen coordinate (150, 250). These properties are set inside the default constructor. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 4 How an instance of Ch 7 JFrame. Subclass 1 will appear on the screen. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame Every method of a superclass is inherited by its subclass. Because the subclass-superclass relationships are formed into an inheritance hierarchy, a subclass inherits all methods defined in its ancestor classes. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame Next we will define another subclass called Ch 7 JFrame. Subclass 2, which will have a white background. We will define this class as an instantiable main class so we don’t have to define a separate main class. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame To make the background white, we must access the frame’s content pane, the area of the frame excluding the title and menu bars and the border. We access the content pane by calling the frame’s get. Content. Pane method. We change the background color by calling the content pane’s set. Background method. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame /* Chapter 7 Sample Program: A simple subclass of JFrame that changes the background color to white. File: Ch 7 JFrame. Subclass 2. java */ import javax. swing. *; import java. awt. *; class Ch 7 JFrame. Subclass 2 extends JFrame { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 200; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.
![7. 1 Creating a Subclass of JFrame public static void main(String[] args) { Ch 7. 1 Creating a Subclass of JFrame public static void main(String[] args) { Ch](http://slidetodoc.com/presentation_image_h/2d60b9f24a3efa0e79a17ece6e14c3f9/image-20.jpg)
7. 1 Creating a Subclass of JFrame public static void main(String[] args) { Ch 7 JFrame. Subclass 2 frame = new Ch 7 JFrame. Subclass 2(); frame. set. Visible(true); } public Ch 7 JFrame. Subclass 2( ) { //set the frame default properties set. Title ( "White Background JFrame Subclass" ); set. Size ( FRAME_WIDTH, FRAME_HEIGHT ); set. Location ); ( FRAME_X_ORIGIN, FRAME_Y_ORIGIN ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 1 Creating a Subclass of JFrame //register 'Exit upon closing' as a default close operation set. Default. Close. Operation( EXIT_ON_CLOSE ); change. Bk. Color( ); } private void change. Bk. Color() { Container content. Pane = get. Content. Pane(); content. Pane. set. Background(Color. white); } } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 5 An instance of Ch 7 JFrame. Subclass 2 that has a white background. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 2 Placing Buttons on the Content Pane of a Frame There are two approaches to placing GUI objects on a frame’s content pane. One approach uses a layout manager, an object that controls the placement of the GUI objects. The other approach uses absolute positioning to explicitly specify the position and size of GUI objects on the content pane. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 2 Placing Buttons on the Content Pane of a Frame To use absolute positioning, set the layout manager of a frame’s content pane to none by passing null to the set. Layout method. content. Pane. set. Layout(null); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 2 Placing Buttons on the Content Pane of a Frame We then place two buttons at the position and size we want by calling the button’s set. Bounds method: ok. Button. set. Bounds( 75, 125, 80, 30); The first two arguments specify the button’s position. The last two arguments specify the width and height of the button. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 2 Placing Buttons on the Content Pane of a Frame To make a button appear on the frame, add it to the content pane by calling the add method. content. Pane. add(ok. Button); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 6 A sample window when it is first opened and after the CANCEL button is clicked. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 7 The process of creating a button and placing it on a frame. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events An action involving a GUI object, such as clicking a button, is called an event. The mechanism to process events is called event handling. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events The event-handling model of Java is based on the concept known as the delegation-based event model. With this model, event handling is implemented by two types of objects: • event source objects • event listener objects. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events An event source object is a GUI object where an event occurs. An event source generates events. An event listener object is an object that includes a method that gets executed in response to the generated events. When an event is generated, the system notifies the relevant event listener objects. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events There are many different kinds of events, but the most common one is an action event. For the generated events to be processed, we must associate, or register, event listeners to the event sources. If event sources have no registered listeners, the generated events are ignored. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events An object that can be registered as an action listener must be an instance of a class that is declared specifically for the purpose. We call such classes action listener classes. To associate an action listener to an action event source, we call the event source’s add. Action. Listener method with the action listener as its argument. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events A single listener can be associated to multiple event sources. Likewise, multiple listeners can be associated to a single event source. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events When an event source generates an event, the system checks for matching registered listeners. If there is no matching listener, the event is ignored. If there is a matching listener, the system notifies the listener by calling the listener’s corresponding method. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events In the case of action events, the method called is action. Performed. To ensure the programmer includes the necessary action. Performed method in the action listener class, the class must be defined in a specific way. import java. awt. event. *; class Button. Handler implements Action. Listener {. . . } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events Action. Listener is an interface, not a class. Like a class, an interface is a reference data type, but unlike a class, an interface includes only constants and abstract methods. An abstract method has only the method header, or prototype; it has no method body. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events A class that implements a Java interface must provide the method body to all the abstract methods defined in the interface. By requiring an object we pass as an argument to the add. Action. Listener method to be an instance of a class that implements the Action. Listener interface, the system ensures that this object will include the necessary action. Performed method. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events To change the title of the frame, depending on which button is clicked, we use the action. Performed method. The method model is: public void action. Performed(Action. Event evt){ String button. Text = get the text of the event source; JFrame frame = the frame that contains this event source; frame. set. Title(“You clicked “ + button. Text); } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events The first statement may be handled in one of two ways. The first way is via the get. Action. Command method of the action event object evt: String button. Text = evt. get. Action. Command(); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events The second way is via the get. Source method of the action event object evt. : JButton clicked. Button = (JButton) evt. get. Source(); String button. Text = clicked. Button. get. Text(); Note that the object returned by the get. Source method may be an instance of any class, so we type cast the returned object to a proper class in order to use the desired method. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events To find the frame that contains the event source, we • get the root pane to which the event source belongs, then • get the frame that contains this root pane. JRoot. Pane root. Pane = clicked. Button. get. Root. Pane(); Frame frame = (JFrame) root. Pane. get. Parent(); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 3 Handling Button Events A frame window contains nested layers of panes. The topmost pane is called the root pane. The frame can be the event listener of the GUI objects it contains. cancel. Button. add. Action. Listener(this); ok. Button. add. Action. Listener(this); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes The Swing GUI classes JLabel, JText. Field, and JText. Area all deal with text. • A JLabel object displays uneditable text. • A JText. Field object allows the user to enter a single line of text. • A JText. Area object allows the user to enter multiple lines of text. It can also be used for displaying multiple lines of uneditable text. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes An instance of JText. Field generates action events when the object is active and the user presses the ENTER key. The action. Performed method must determine which of the three event sources in our example (two buttons and one text field) generated the event. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes The instanceof operator determines the class to which the event source belongs. The general model is thus: if (event. get. Source() instanceof JButton ){ //event source is either cancel. Button //or ok. Button. . . } else { //event source must be input. Line. . . } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes The get. Text method of JText. Field may be used to retrieve the text that the user entered. public void action. Performed(Action. Event event){ if (event. get. Source() instanceof JButton){ JButton clicked. Button = (JButton) event. get. Source(); String button. Text = clicked. Button. get. Text(); set. Title(“You clicked ” + button. Text); } else {//the event source is input. Line set. Title(“You entered ‘” + input. Line. get. Text() + “’”); } } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes A JLabel object is useful for displaying a label indicating the purpose of another object, such as a JText. Field object. prompt = new JLabel(“Please enter your name”); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes JLabel objects may also be used to display images. When a JLabel object is created, we can pass an Image. Icon object instead of a string. To create the Image. Icon object, we must specify the filename of the image. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes We declare the data member private JLabel image; then create it in the constructor as public Ch 7 Text. Frame 2{. . . image = new JLabel(new Image. Icon(“cat. gif”); //note that this assumes the. gif is //in the same directory as the program image. set. Bounds(10, 20, 50); content. Pane. add(image); . . . } ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 8 The Ch 7 Text. Frame 2 window with one text JLabel, one image JLabel, one JText. Field, and two JButton objects. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes Next we will declare a JText. Area object: private JText. Area text. Area; and add statements to create it inside the constructor: text. Area = new JText. Area(); text. Area. set. Bounds(50, 5, 200, 135); text. Area. set. Border(Border. Factory. create. Line Border(Color. red)); text. Area. set. Editable(false); content. Pane. add(text. Area); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes We call the create. Line. Border method of the Border. Factory class, because by default the rectangle indicating the boundary of the JText. Area object is not shown on the screen. We disable editing of the text area in the statement text. Area. set. Editable(false); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes The append method allows us to add text to the text area without replacing old content. Using the set. Text method of JText. Area will replace old content with new content. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes We want to ensure the program will behave consistently across all operating systems. The control character n will not permit consistent behavior. Instead, we will implement: private static final String NEWLINE = System. get. Property(“line. separator”); as text. Area. append(entered. Text + NEWLINE); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 9 The state of a Ch 7 Text. Frame window after six words are entered. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 4 JLabel, JText. Field, and JText. Area Classes To add scroll bars to the JText. Area object, we amend the earlier code as follows: text. Area = new JText. Area(); text. Area. set. Editable(false); JScroll. Pane scroll. Text = new JScroll. Pane(text. Area); text. Area. set. Bounds(50, 5, 200, 135); text. Area. set. Border(Border. Factory. create. Line Border(Color. red)); content. Pane. add(scroll. Text); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 7. 10 A sample Ch 7 Text. Frame 3 window when the JScroll. Pane GUI object is used. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus The javax. swing package contains three useful menu-related classes: JMenu. Bar, JMenu, and JMenu. Item. • Menu. Bar is a bar where the menus are placed. • Menu (such as File or Edit) is a single item in the Menu. Bar. • Menu. Item (such as Copy, Cut, or Paste) is an individual menu choice in the Menu. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus When a Menu. Item is selected, it generates a menu action event. We process menu selections by registering an action listener to menu items. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus The following example will create the two menus below and illustrate how to display and process the menu item selections. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus We will follow this sequence of steps: 1. Create a JMenu. Bar object and attach it to a frame. 2. Create a JMenu object. 3. Create JMenu. Item objects and add them to the JMenu object. 4. Attach the JMenu object to the JMenu. Bar object. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus We create a file. Menu object as file. Menu = new Menu(“File”); The argument to the Menu constructor is the name of the menu. Menu items appear from the top in the order in which they were added to the menu. ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus To create and add a menu item New to file. Menu, we execute item = new Menu. Item(“New”); item. add. Action. Listener(this); file. Menu. add(item); And to add a horizontal line as a separator between menu items, we execute file. Menu. add. Separator(); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.

7. 5 Menus We then attach the menus to a menu bar. We create a Menu. Bar object in the constructor, call the frame’s set. Menu. Bar method to attach it to the frame, and add the two Menu objects to the menu bar. Menu. Bar menu. Bar = new Menu. Bar(); set. Menu. Bar(menu. Bar); menu. Bar. add(file. Menu); menu. Bar. add(edit. Menu); ©The. Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display.
- Slides: 65