Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Advanced GUI.

Similar presentations


Presentation on theme: "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Advanced GUI."— Presentation transcript:

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Advanced GUI

2 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Objectives After you have read and studied this chapter, you should be able to Arrange GUI objects on a container, using layout managers and nested panels. Write GUI application programs that process mouse events. Understand how the SketchPad class introduced in Chapter 2 is implemented.

3 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Objectives After you have read and studied this chapter, you should be able to Write GUI application programs with JCheckBox, JRadioButton, JComboBox, JList, and JSlider objects. Develop programs using a variation of the model-view-controller (MVC) design pattern.

4 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events Mouse events include such user interactions as moving the mouse, dragging the mouse, and clicking the mouse buttons. To study these events, we will define a subclass of JFrame that handles the left mouse button click events. The subclass of JFrame we will define is named Ch14TrackMouseFrame.

5 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events A Ch14TrackMouseFrame object is an event source of mouse events. We will allow this object to be an event listener as well. Its class must therefore implement the MouseListener interface. Class Ch14TrackMouseFrame extends Frame implements MouseListener { … }

6 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events The MouseListener interface has five abstract methods: mouseClicked mouseEntered mouseExited mousePressed mouseReleased The argument to all five methods is an instance of MouseEvent.

7 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events The mouseClicked method is called every time the left mouse button is clicked, or pressed down and released. The getX and getY methods of MouseEvent retrieve the x and y coordinate values of wherever the mouse is clicked.

8 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events If we want to detect the mouse button press and release separately, we can provide a method body to the mousePressed and mouseReleased methods, respectively.

9 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events The getClickCount method of MouseEvent will detect the number of mouse clicks performed, so different events may be triggered by a single click or double click, for example.

10 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events Implementing the MouseMotionListener interface will allow us to track mouse dragging. The MouseMotionListener interface has two abstract methods: mouseDragged mouseMoved The argument to both methods is an instance of MouseEvent.

11 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events When either the right or left mouse button is pressed, the event listeners mousePressed method is called. To determine which mouse button is pressed inside the mousePressed method, we call the isMetaDown method of MouseEvent. The isMetaDown method returns true if the right button is pressed.

12 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events Similar to the mousePressed method, the mouseDragged method is called whether the mouse was dragged with the left or right button. The isMetaDown method may also be used here to determine which button was used to drag the mouse.

13 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events We now have the tools to understand the implementation of the SketchPad class from Chapter 2. Following is the fully implemented program.

14 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events /* File: Ch14SketchPad.java */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14SketchPad extends JFrame implements MouseListener, MouseMotionListener { private static final int FRAME_WIDTH = 450; private static final int FRAME_HEIGHT = 300; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private int last_x; private int last_y;

15 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events public static void main(String[] args) { Ch14SketchPad frame = new Ch14SketchPad(); frame.setVisible(true); } public Ch14SketchPad( ) { //set frame properties setTitle ("Chapter 14 SketchPad"); setSize ( FRAME_WIDTH, FRAME_HEIGHT ); setResizable( false ); setLocation ( FRAME_X_ORIGIN, FRAME_Y_ORIGIN ); setDefaultCloseOperation(EXIT_ON_CLOSE); last_x = last_y = 0; addMouseListener( this ); addMouseMotionListener( this ); }

16 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events public void mousePressed( MouseEvent event ) { int x = event.getX(); int y = event.getY(); if ( event.isMetaDown() ) { //the right mouse button is pressed, so //erase the contents Graphics g = getGraphics(); Rectangle r = getBounds(); g.clearRect(0, 0, r.width, r.height); g.dispose(); } else { //the left mouse button is pressed, //remember the starting point of a new //mouse drag last_x = x; last_y = y; }

17 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Handling Mouse Events public void mouseClicked ( MouseEvent event ) { } public void mouseEntered ( MouseEvent event ) { } public void mouseExited ( MouseEvent event ) { } public void mouseReleased( MouseEvent event ) { } public void mouseDragged( MouseEvent event ) { int x = event.getX(); int y = event.getY(); if ( !event.isMetaDown() ) { //dont process the right button drag Graphics g = getGraphics(); g.drawLine(last_x, last_y, x, y); g.dispose(); last_x = x; last_y = y; } public void mouseMoved ( MouseEvent event ) { } }

18 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels For building practical GUI-based Java programs, we must learn how to use layout managers effectively. We will begin by covering the three basic managers: FlowLayout BorderLayout GridLayout

19 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels The default content pane of a frame is an instance of JPanel. We can place a JPanel inside another JPanel. Each of these nesting panels may be assigned a different layout manager. The capability of nesting panels with different layout managers presents opportunities for creating intricate layouts on a frame.

20 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels The most basic layout is java.awt.FlowLayout. In this layout, GUI components are placed in left-to-right order. As a default, components on each line are centered. When the frame containing the component is resized, the placement of the components is adjusted accordingly.

21 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels We first assign the desired layout manager to the container (in this case, the content pane of a frame) in the frames constructor. Container contentPane = getContentPane();... contentPane.setLayout(new FlowLayout()); A container has a default layout manager assigned to it, but it is safer to explicitly assign the desired layout manager ourselves.

22 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels We then create five buttons and add them to the content pane. JButton button1, button2, button3, button4, button5;... button1 = new JButton(button1);... contentPane.add(button1);...

23 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Placement of five buttons by using FlowLayout when the frame is first opened and after the frame is resized.

24 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels The second layout manager is java.awt.BorderLayout. This manager divides the container into five regions: Center North South East West

25 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels We set the BorderLayout as contentPane.setLayout(new BorderLayout()); And place GUI components with the second argument specifying the region: contentPane.add(button1,BorderLayout.NORTH); contentPane.add(button1,BorderLayout.SOUTH);

26 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Placement of five buttons by using BorderLayout when the frame is first opened and after the frame is resized.

27 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Placement of two buttons by using BorderLayout. Buttons are placed on the center and east regions.

28 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels The default of BorderLayout has no gaps between the regions. We can specify the amount of vertical and horizontal gaps between the regions in pixels. contentPane.setLayout(new BorderLayout(10, 20));

29 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels The third layout manager is java.awt.GridLayout. This manager places GUI components on equal-sized N × M grids. Components are placed in top-to- bottom, left-to-right order.

30 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Placement of five buttons by using GridLayout of two rows and three columns when the frame is first opened and after the frame is resized.

31 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels To create a GridLayout object, we pass two arguments: Number of rows Number of columns contentPane.setLayout(new GridLayout(2, 3)); We then place GUI components in the manner analogous to the one used for FlowLayout.

32 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Layout Managers and Panels If the value provided for the number of rows is nonzero, the value we specify for the columns is irrelevant. The layout will create the designated number of rows and adjust the number of columns so that all components will fit in the designated number of rows.

33 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels It is possible, but very difficult, to place all GUI components on a single JPanel or other types of containers. A better approach is to use multiple panels, placing panels inside other panels.

34 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels To illustrate this technique, we will create two sample frames that contain nested panels. The samples will provide the interface for playing Tic Tac Toe and HiLo.

35 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A sample frame that contains nested panels. Four JPanel objects are used in this frame.

36 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Another sample frame that contains nested panels. Five JPanel objects are used in this frame.

37 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The topmost panel in Fig is the content pane of the frame. It has a border layout. The content panes center region contains an instance of Ch14TicTacToePanel named gamePanel.

38 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The content panes east region is occupied by an instance of another JPanel named controlPanel. A border layout is used for this panel. The north region of controlPanel is occupied by another JPanel named scorePanel. The south region is occupied by a JButton.

39 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The layout for scorePanel is set to a grid layout with four grids, each occupied by a JLabel object. The nesting relationship is illustrated in Fig

40 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig This diagram shows how the panels of the frame in Fig are nested.

41 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels When we nest panels, it is useful to mark their borders. The BorderFactory class contains many different border formats, such as titled border lowered bevel border line border etc.

42 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels We create a titled border by calling the class method createTitledBorder of the BorderFactory class. scorePanel.setBorder(BorderFactory. createTitledBorder(Scores: )); gamePanel.setBorder(BorderFactory. createLoweredBevelBorder()); Following is the program listing that creates the visual aspect of the program (i.e., there is no code for handling events or game logic).

43 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels /* File: Ch14NestedPanels1.java */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14NestedPanels1 extends JFrame { private static final int FRAME_WIDTH = 500; private static final int FRAME_HEIGHT = 350; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; public static void main(String[] args) { Ch14NestedPanels1 frame = new Ch14NestedPanels1(); frame.setVisible(true); }

44 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels public Ch14NestedPanels1() { Container contentPane; Ch14TicTacToePanel gamePanel; JPanel controlPanel; JPanel scorePanel; //set the frame properties setSize (FRAME_WIDTH, FRAME_HEIGHT); setTitle ("Program Ch14NestedPanels1"); setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane( ); contentPane.setLayout(new BorderLayout(10, 0)); gamePanel = new Ch14TicTacToePanel(); gamePanel.setBorder(BorderFactory. createLoweredBevelBorder()); controlPanel = new JPanel(); controlPanel.setLayout(new BorderLayout( ));

45 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels contentPane.add(gamePanel, BorderLayout.CENTER); contentPane.add(controlPanel, BorderLayout.EAST); scorePanel = new JPanel(); scorePanel.setBorder( BorderFactory.createTitledBorder("Scores:")); scorePanel.setLayout(new GridLayout(2, 2)); scorePanel.add(new JLabel("Player 1:")); scorePanel.add(new JLabel(" 0")); scorePanel.add(new JLabel("Player 2:")); scorePanel.add(new JLabel(" 0")); controlPanel.add(scorePanel,BorderLayout.NORTH); controlPanel.add(new JButton("New Game"), BorderLayout.SOUTH); //register 'Exit upon closing' as a default //close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); }

46 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels For the second sample frame, we will use the nested panels shown in Fig Again, this program illustrates only how the interface is built. It does not contain any game logic.

47 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig The nested panels and associated layout managers for HiLoDisplay.

48 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels /* File: Ch14NestedPanels2.java */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14NestedPanels2 extends JFrame { private static final int FRAME_WIDTH = 250; private static final int FRAME_HEIGHT = 270; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private final String ENTER = "Enter"; private final String CANCEL = "Cancel"; private final String BLANK = ""; private JTextField guessEntry; private JLabel hint;

49 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels public static void main(String[] args) { Ch14NestedPanels2 frame = new Ch14NestedPanels2(); frame.setVisible(true); } public Ch14NestedPanels2( ) { JPanel guessPanel, hintPanel, controlPanel, buttonPanel; JButton enterBtn, cancelBtn; Container contentPane; //set the frame properties setSize (FRAME_WIDTH, FRAME_HEIGHT); setTitle ("Program Ch14NestedPanels2"); setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane( ); contentPane.setLayout(new GridLayout(3, 1)); guessPanel = new JPanel();

50 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels guessPanel.setBorder(BorderFactory. createTitledBorder("Your Guess")); guessPanel.add(guessEntry = new JTextField(10)); hintPanel = new JPanel(); hintPanel.setBorder(BorderFactory. createTitledBorder("Hint")); hintPanel.add(hint = new JLabel("Let's Play HiLo")); controlPanel = new JPanel(new BorderLayout()); buttonPanel = new JPanel(); buttonPanel.add(enterBtn = new JButton(ENTER)); buttonPanel.add(cancelBtn = new JButton(CANCEL)); controlPanel.add(buttonPanel,BorderLayout.SOUTH); contentPane.add(guessPanel); contentPane.add(hintPanel); contentPane.add(controlPanel); }

51 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels There are two ways to approach designing the Tic Tac Toe board of N × N = N 2 cells. The panel handles the mouse click events, so every time the player clicks on a cell, a circle or cross is displayed. However, the panel illustrated here does not contain any game logic.

52 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The first approach is to compute the origin point (the top left corner) of each cell based on the dimension of the panel and the number of cells in the panel. When we know the origin point of a cell, we can draw a circle or cross by using the drawLine or drawOval method.

53 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels When a cell is clicked, we get the x and y coordinates of the mouse click location and determine in which cell the mouse click event has occurred. When we know the cell, we use its origin point to draw a circle or cross at the correct position and size.

54 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig The approach not adopted here. The panel is divided into equal-size cells. A circle or cross can be drawn using the drawOval or drawLine method.

55 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The second approach uses nested panels. We will define two classes, Ch14TicTacToePanel and Ch14TicTacToeCell. An instance of Ch14TicTacToePanel will contain N 2 instances of Ch14TicTacToeCell, each representing a single cell in the board.

56 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels A Ch14TicTacToeCell object contains one component, an instance of JLabel. Instead of assigning text to the JLabel, we assign an image icon to this object. There are three image files: circle.gif cross.gif blank.gif.

57 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Effective Use of Nested Panels The Ch14TicTacToePanels main tasks are to handle the layout of N 2 Cell objects and the mouse click events. The GridLayout manager is perfect to use in this case. Each cell is the source of mouse events, and the container of the cells is the mouse event listener.

58 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components You are already acquainted with Swing components JButton and JTextField. We will now examine the basic capabilities of some additional Swing components that will be helpful in building your applications.

59 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The JCheckBox class is used to represent check-box buttons. Check-boxes are useful for presenting binary options (yes/no, true/false, etc.) To create a check-box button with the text Java, we write JCheckBox cbBtn = new JCheckBox(Java);

60 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A frame with four check box buttons and one pushbutton.

61 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components To check if a check-box button is selected or deselected, we call its isSelected method: if (cbBtn.isSelected()){ System.out.println(You can program in + cbBtn.getText()); }else{... }

62 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components A JCheckBox object generates both action events and item events. It is not common to associate action listeners to JCheckBox objects. An item event is generated when the state (selected or deselected) of a check-box button changes.

63 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components We can register an instance of a class that implements the ItemListener interface as an item listener of a JCheckBox object. When an item event is generated, its itemStateChanged method is called.

64 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The JRadioButton class is used to represent a radio button. Radio buttons may be selected or deselected, but unlike check boxes, only one radio button in a group may be selected at any time. When we select one radio button in a group, any other selected radio button in that group is deselected.

65 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A frame with four radio buttons and one pushbutton.

66 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components Radio buttons are useful in allowing the user to select one of a list of possible choices. Radio buttons are used in a manner very similar to that of check boxes. They also generate both action and item events. But radio buttons, unlike check boxes, must be added to a button group.

67 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The JComboBox class presents a combo box. This class, like JRadioButton, allows the user to select one of a list of possible choices.

68 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The main difference between JComboBox and JRadioButton is in how the options are presented to the user. The JComboBox presents the options to the user in a drop-down list.

69 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components We can construct a new JComboBox by passing an array of String objects: String[] comboBoxItem = {Java, C++, Smalltalk, Ada}; JComboBox comboBox = new JComboBox(comboBoxItem);

70 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A frame with one combo box (drop-down list) and one pushbutton.

71 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components A JComboBox object generates action and item events. To find out the currently selected item, we call the getSelectedItem method of JComboBox.

72 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The JList class is useful when we need to display a list of items. We can construct a JList object similarly to the way we construct a JComboBox object: String[] names = {Ape, Bat, Bee, Cat, Dog, Eel, Fox, Gnu, Hen, Man, Sow, Yak}; JList list = new JList(names);

73 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A frame with one list and one pushbutton.

74 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components With JList, we have an option of specifying one of three selection modes: single-selection single-interval multiple-interval

75 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The single-selection mode allows the user to select only one item at a time. The single-interval mode allows the user to select a single contiguous interval. The multiple-interval mode is the default mode. It allows the user to select multiple contiguous intervals (each interval will include one or more items).

76 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The following statements demonstrate how to set the different modes: list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); list.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_ SELECTION); list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_ SELECTION);

77 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components The JSlider class represents a slider in which the user can move a nob to a desired position. The position of the nob on the slider determines the selected value.

78 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Other GUI Components When a nob is moved, a JSlider object generates a change event (this event occurs when there is a change in the event source). The event listener for this object must implement the ChangeListener interface.

79 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A frame with three vertical sliders for setting an RGB value.


Download ppt "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 Advanced GUI."

Similar presentations


Ads by Google