Download presentation
Presentation is loading. Please wait.
1
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 1 Chapter 14 GUI and Event-Driven Programming
2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 2 What is a GUI program? Window-based –contains menus, buttons, text fields, … User interacts with program using mouse as well as keyboard User determines order in which things get done
3
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 3 Graphical User Interfaces Implemented by using classes from two packages. –javax.swing –java.awt GUI is constructed from Components –Top-level component is a Container which can hold other components –Light-weight containers can be used to organize other components –Simple components include buttons, text boxes, menus, etc. LayoutManager controls how Components are laid out within a container
4
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 4 JFrame The JFrame class contains rudimentary functionalities to support features found in any frame window. A JFrame is a Container The main window for a GUI applicationis generally a JFrame –One approach is to use the JFrame class and add custom components to it –For more flexibility, we can define a subclass of the JFrame class.
5
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 5 Creating a Subclass public class JFrameSubclass extends JFrame { public JFrameSubclass { // set up the JFrame // add components // implement desired behavior }
6
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 6 The Content Pane of a JFrame A JFrame is a Container but we don't add Components to it directly. Every JFrame has a ContentPane –The content pane is where we put GUI objects such as buttons, labels, scroll bars, and others. –We access the content pane by calling the frame’s getContentPane() method. –We can use setContentPane() to use our own container classes (extending JPanel) instead of the default one A JFrame also has a MenuBar –We can add Menus to the MenuBar –We can add MenuItems and other Menus to a Menu
7
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 7 Java Containers JPanel - use with a layout manager to organize other components JScrollPane - provides scrollbars for a single component JSplitPane - a container that holds two components –Putting a JSplitPane in each section allows for more components JTabbedPane - layers multiple components
8
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 8 Adding Components to a Container The Container classes have an add method that can be used to add Components. Container contentPane = getContentPane(); JButton okButton = new JButton("OK"); contentPane.add(okButton); contentPane.add( new JLabel( "label text")); JTextField inputBox = new JTextField( numChars); contentPane.add(inputBox); Components generally appear in the order they are added –Component placement is controlled by a layout manager
9
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 9 Java Components Buttons –JButton can display text and or image –JCheckBox has two states Text Components –JTextField –JTextArea –JLabel Components for selection –JRadioButton and ButtonGroup –JComboBox –JList Others –JSlider –JSpinner
10
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 10 Event Handling 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 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
11
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 11 Event Source Objects An event source is a GUI object which generates events. –Buttons, text boxes, list boxes, and menus are common event sources in GUI-based applications. An event listener object is an object that includes a method that gets executed in response to the generated events. –A listener must be registered, to a source, so it can be notified when the source generates events. –Use an interface to guarantee that the listener object has the appropriate method
12
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 12 Connecting Source and Listener JButton Handler event source event listener notify register A listener must be registered to a event source. Once registered, it will get notified when the event source generates events.
13
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 13 Registration and notification are specific to event types MouseListener handles mouse events ItemListener handles item selection events ActionListener handles button and menu events Event listeners implement a listener interface public class ButtonHandler implements ActionListener {... } Register a Listener with an event generator with an add___Listener method JButton button = new JButton("OK"); ButtonHandler handler = new ButtonHandler( ); button.addActionListener(handler); Event Types
14
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 14 Listener Interfaces A Java interface includes only constants and abstract methods. A Java interface specifies a behavior. A class implements an interface by providing the method body to the abstract methods stated in the interface. –Any class can implement the interface. The ActionListener interface includes one method named actionPerformed. –A class that implements the ActionListener interface must define actionPerformed. –This is where we put a code we want to be executed in response to the generated events.
15
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 15 Two Approaches to Listeners Define a separate class –ButtonHandler and Ch14JButtonEvents –A separate class doesn't have access to the data of the JFrame class unless it is defined inside the JFrame class Let the JFrame implement the listener interface public class Ch14JButtonFrameHandler extends JFrame implements ActionListener {... public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); // code to implement the desired response }}
16
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 16 Component Classes for Handling Text The Swing GUI classes JLabel, JTextField, and JTextArea deal with text. A JLabel object displays uneditable text (or image). A JTextField object allows the user to enter a single line of text. –generates ActionEvent when user presses return key A JTextArea object allows the user to enter multiple lines of text. It can also be used for displaying multiple lines of uneditable text. –Use the setText and append methods to control content –If the JTextArea is editable, user can type into it
17
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 17 Using Scroll Bars A JTextArea does not have scroll bars. To allow scrolling of any component, we add the component to a JScrollPane. JTextArea textArea = new JTextArea();... JScrollPane scrollText = new JScrollPane(textArea);... contentPane.add(scrollText);
18
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 18 Other Common GUI Components JCheckBox (generates ItemEvent and ActionEvent) –see Ch14JCheckBoxSample1.java and Ch14JCheckBoxSample2.java JRadioButton (generates ItemEvent and ActionEvent, use in conjunction with ButtonGroup) –see Ch14JRadioButtonSample.java JComboBox (generates ItemEvent and ActionEvent) –see Ch14JComboBoxSample.java Jlist (generates ActionEvent) –see Ch14JListSample.java Jslider (generates ChangeEvent) –see Ch14JSliderSample.java
19
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 19 Layout Managers The layout manager determines how the GUI components are added to the container (such as the content pane of a frame) Among the many different layout managers, the common ones are –FlowLayout (see Ch14FlowLayoutSample.java) –BorderLayout (see Ch14BorderLayoutSample.java) –GridLayout (see Ch14GridLayoutSample.java) –BoxLayout (see guiExtras/BoxLayoutSample.java)
20
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 20 FlowLayout In using this layout, GUI componentsare placed in left- to-right order. –When the component does not fit on the same line, left-to- right placement continues on the next line. As a default, components on each line are centered. When the frame containing the component is resized, the placement of components is adjusted accordingly. Creating a FlowLayout contentPane.setLayout( new FlowLayout());
21
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 21 BorderLayout This layout manager divides the container into five regions: center, north, south, east, and west. –The north and south regions expand or shrink in height only –The east and west regions expand or shrink in width only –The center region expands or shrinks on both height and width. Not all regions have to be occupied. Creating a BorderLayout – contentPane.setLayout( new BorderLayout()); Only one component can be added to each area – contentPane.add( component, BorderLayout.CENTER);
22
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 22 GridLayout This layout manager placesGUI components on equal- size N by M grids. Components are placed in top-to-bottom, left-to-right order. The number of rows and columns remains the same after the frame is resized, but the width and height of each region will change. Creating a GridLayout contentPane.setLayout( new GridLayout(rows, cols));
23
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 23 BoxLayout BoxLayout is in the swing package It allows you to arrange components either horizontally (BoxLayout.X_AXIS) or vertically (BoxLayout.Y_AXIS). The constructor needs a reference to the container contentPane.setLayout( new BoxLayout( contentPane, BoxLayout.X_AXIS)); Use Box class to create space between components NOTE: This is not in your text
24
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 24 Nesting Containers It is not always easy to place all GUI components on a single JPanel and get them organized in a pleasing way. Containers can be nested so that different areas can be organized differently. –Ch14NestedPanels1.java provides the user interface for playing Tic Tac Toe. –Ch14NestedPanels2.java provides the user interface for playing HiLo. JSplitPane is a container that holds exactly two components –The two sections can be side-by-side or one above the other –See guiExtras/SplitFrame.java
25
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 25 Menus The javax.swing package contains three menu-related classes: JMenuBar, JMenu, and JMenuItem. JMenuBar is a bar where the menus are placed. There is one menu bar per frame. JMenu (such as File or Edit) is a group of menu choices. JMenuBar may include many JMenu objects. JMenuItem (such as Copy, Cut, or Paste) is an individual menu choice in a JMenu object. Only the JMenuItem objects generate events.
26
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 26 Sequence for Creating Menus 1.Create a JMenuBar object and attach it to a frame. 2.Create a JMenu object. 3.Create JMenuItem objects and add them to the JMenu object. 4.Attach the JMenu object to the JMenuBar object.
27
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 27 File Handling in a GUI Program The JFileChooser class (javax.swing package) has methods that create dialog boxes for selecting files public int showOpenDialog( Component parent) public int showSaveDialog( Component parent) –return value indicates which buton was used to close the dialog –Use chooser.getSelectedFile() to get a reference to the selected file By default, the dialogs show the user's home directory You can specify a path in the constructor public JFileChooser( File currentDirectory)
28
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 28 Handling Mouse Events Mouse events include such user interactions as –moving the mouse –dragging the mouse (moving the mouse while the mouse button is being pressed) –clicking the mouse buttons. The MouseListener interface handles mouse button –mouseClicked, mouseEntered, mouseExited, mousePressed, and mouseReleased The MouseMotionListener interface handles mouse movement –mouseDragged and mouseMoved. See Ch14TrackMouseFrame and Ch14SketchPad
29
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 14 - 29 etc. Key Events Timer
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.