Bài giảng Chapter 7: Event-Driven Programming and Basic GUI Objects

Tài liệu Bài giảng Chapter 7: Event-Driven Programming and Basic GUI Objects: Chapter 7Event-Driven Programming and Basic GUI Objects©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 7 ObjectivesAfter you have read and studied this chapter, you should be able toDefine a subclass of the JFrame class, using inheritance.Write graphical user interface (GUI) application programs using JButton, JLabel, ImageIcon, JTextField, and JTextArea objects from the javax.swing package.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 7 ObjectivesAfter you have read and studied this chapter, you should be able toWrite GUI application programs with menus, using menu objects from the javax.swing package.Write event-driven programs, using Java’s delegation-based event model.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.IntroductionThis chapter covers the graphical user interface (GUI). In Java, GUI-based programs are implemented by using classes from the javax.swing and jav...

ppt65 trang | Chia sẻ: honghanh66 | Lượt xem: 901 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Chapter 7: Event-Driven Programming and Basic GUI Objects, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 7Event-Driven Programming and Basic GUI Objects©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 7 ObjectivesAfter you have read and studied this chapter, you should be able toDefine a subclass of the JFrame class, using inheritance.Write graphical user interface (GUI) application programs using JButton, JLabel, ImageIcon, JTextField, and JTextArea objects from the javax.swing package.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 7 ObjectivesAfter you have read and studied this chapter, you should be able toWrite GUI application programs with menus, using menu objects from the javax.swing package.Write event-driven programs, using Java’s delegation-based event model.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.IntroductionThis 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.1Various GUI objects from the javax.swing package.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.IntroductionAWT 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.IntroductionTo 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameAs 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.2The inheritance hierarchy of JOptionPane as shown in the API documentation.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameTo 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrame/*Chapter 7 Sample Program: Displays a default JFrame windowFile: Ch7DefaultJFrame.java*/import javax.swing.*;class Ch7DefaultJFrame { public static void main( String[] args ) { JFrame defaultJFrame; defaultJFrame = new JFrame(); defaultJFrame.setVisible(true); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.3A default JFrame window appears at the top left corner of the screen.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameTo define a subclass of another class, we declare the subclass with the reserved word extends.class Ch7JFrameSubclass1 extends JFrame {...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameWe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.4How an instance of Ch7JFrameSubclass1 will appear on the screen.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameEvery 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameNext we will define another subclass called Ch7JFrameSubclass2, 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFrameTo 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 getContentPane method. We change the background color by calling the content pane’s setBackground method.©TheMcGraw-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: Ch7JFrameSubclass2.java*/import javax.swing.*;import java.awt.*;class Ch7JFrameSubclass2 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;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.1 Creating a Subclass of JFramepublic static void main(String[] args) { Ch7JFrameSubclass2 frame = new Ch7JFrameSubclass2(); frame.setVisible(true); }public Ch7JFrameSubclass2( ) {//set the frame default properties setTitle ( "White Background JFrame Subclass" ); setSize ( FRAME_WIDTH, FRAME_HEIGHT ); setLocation ( FRAME_X_ORIGIN, FRAME_Y_ORIGIN );©TheMcGraw-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 setDefaultCloseOperation( EXIT_ON_CLOSE ); changeBkColor( );}private void changeBkColor() { Container contentPane = getContentPane(); contentPane.setBackground(Color.white); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.5An instance of Ch7JFrameSubclass2 that has a white background.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.2 Placing Buttons on the Content Pane of a FrameThere 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.2 Placing Buttons on the Content Pane of a FrameTo use absolute positioning, set the layout manager of a frame’s content pane to none by passing null to the setLayout method.contentPane.setLayout(null);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.2 Placing Buttons on the Content Pane of a FrameWe then place two buttons at the position and size we want by calling the button’s setBounds method:okButton.setBounds( 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.2 Placing Buttons on the Content Pane of a FrameTo make a button appear on the frame, add it to the content pane by calling the add method.contentPane.add(okButton);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.6A sample window when it is first opened and after the CANCEL button is clicked.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.7The process of creating a button and placing it on a frame.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsAn action involving a GUI object, such as clicking a button, is called an event.The mechanism to process events is called event handling.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsAn 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsThere 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsAn 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 addActionListener method with the action listener as its argument.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsA single listener can be associated to multiple event sources. Likewise, multiple listeners can be associated to a single event source.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsWhen 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsIn the case of action events, the method called is actionPerformed. To ensure the programmer includes the necessary actionPerformed method in the action listener class, the class must be defined in a specific way. import java.awt.event.*;class ButtonHandler implements ActionListener {...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsActionListener 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsA 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 addActionListener method to be an instance of a class that implements the ActionListener interface, the system ensures that this object will include the necessary actionPerformed method.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsTo change the title of the frame, depending on which button is clicked, we use the actionPerformed method. The method model is:public void actionPerformed(ActionEvent evt){ String buttonText = get the text of the event source; JFrame frame = the frame that contains this event source; frame.setTitle(“You clicked “ + buttonText);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsThe first statement may be handled in one of two ways. The first way is via the getActionCommand method of the action event object evt:String buttonText = evt.getActionCommand();©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsThe second way is via the getSource method of the action event object evt.:JButton clickedButton = (JButton) evt.getSource();String buttonText = clickedButton.getText();Note that the object returned by the getSource 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsTo 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. JRootPane rootPane = clickedButton.getRootPane();Frame frame = (JFrame) rootPane.getParent();©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.3 Handling Button EventsA 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.cancelButton.addActionListener(this);okButton.addActionListener(this);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesThe Swing GUI classes JLabel, JTextField, and JTextArea all deal with text. A JLabel object displays uneditable text. A JTextField object allows the user to enter a single line of text. A JTextArea object allows the user to enter multiple lines of text. It can also be used for displaying multiple lines of uneditable text.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesAn instance of JTextField generates action events when the object is active and the user presses the ENTER key.The actionPerformed method must determine which of the three event sources in our example (two buttons and one text field) generated the event. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesThe instanceof operator determines the class to which the event source belongs. The general model is thus:if (event.getSource() instanceof JButton ){//event source is either cancelButton//or okButton...}else { //event source must be inputLine...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesThe getText method of JTextField may be used to retrieve the text that the user entered.public void actionPerformed(ActionEvent event){ if (event.getSource() instanceof JButton){ JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); setTitle(“You clicked ” + buttonText);} else {//the event source is inputLine setTitle(“You entered ‘” + inputLine.getText() + “’”); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesA JLabel object is useful for displaying a label indicating the purpose of another object, such as a JTextField object.prompt = new JLabel(“Please enter your name”);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesJLabel objects may also be used to display images. When a JLabel object is created, we can pass an ImageIcon object instead of a string. To create the ImageIcon object, we must specify the filename of the image.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesWe declare the data memberprivate JLabel image;then create it in the constructor aspublic Ch7TextFrame2{... image = new JLabel(new ImageIcon(“cat.gif”); //note that this assumes the .gif is //in the same directory as the program image.setBounds(10, 20, 50, 50); contentPane.add(image);...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.8The Ch7TextFrame2 window with one text JLabel, one image JLabel, one JTextField, and two JButton objects.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesNext we will declare a JTextArea object:private JTextArea textArea;and add statements to create it inside the constructor:textArea = new JTextArea();textArea.setBounds(50, 5, 200, 135);textArea.setBorder(BorderFactory.createLineBorder(Color.red));textArea.setEditable(false);contentPane.add(textArea);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesWe call the createLineBorder method of the BorderFactory class, because by default the rectangle indicating the boundary of the JTextArea object is not shown on the screen.We disable editing of the text area in the statementtextArea.setEditable(false);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesThe append method allows us to add text to the text area without replacing old content. Using the setText method of JTextArea will replace old content with new content.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesWe 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.getProperty(“line.separator”);astextArea.append(enteredText + NEWLINE);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.9The state of a Ch7TextFrame window after six words are entered.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.4 JLabel, JTextField, and JTextArea ClassesTo add scroll bars to the JTextArea object, we amend the earlier code as follows:textArea = new JTextArea();textArea.setEditable(false);JScrollPane scrollText = new JScrollPane(textArea);textArea.setBounds(50, 5, 200, 135);textArea.setBorder(BorderFactory.createLine Border(Color.red));contentPane.add(scrollText);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 7.10A sample Ch7TextFrame3 window when the JScrollPane GUI object is used.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusThe javax.swing package contains three useful menu-related classes: JMenuBar, JMenu, and JMenuItem.MenuBar is a bar where the menus are placed.Menu (such as File or Edit) is a single item in the MenuBar.MenuItem (such as Copy, Cut, or Paste) is an individual menu choice in the Menu.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusWhen a MenuItem is selected, it generates a menu action event. We process menu selections by registering an action listener to menu items.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusThe following example will create the two menus below and illustrate how to display and process the menu item selections.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusWe will follow this sequence of steps:Create a JMenuBar object and attach it to a frame.Create a JMenu object.Create JMenuItem objects and add them to the JMenu object.Attach the JMenu object to the JMenuBar object.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusWe create a fileMenu object asfileMenu = 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusTo create and add a menu item New to fileMenu, we executeitem = new MenuItem(“New”);item.addActionListener(this);fileMenu.add(item);And to add a horizontal line as a separator between menu items, we executefileMenu.addSeparator();©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.7.5 MenusWe then attach the menus to a menu bar. We create a MenuBar object in the constructor, call the frame’s setMenuBar method to attach it to the frame, and add the two Menu objects to the menu bar.MenuBar menuBar = new MenuBar();setMenuBar(menuBar);menuBar.add(fileMenu);menuBar.add(editMenu);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Các file đính kèm theo tài liệu này:

  • pptchapter_7_3785.ppt