Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14 Advanced GUI. Topics Mouse Events –MouseListener –MouseMotionListener JPanels Layout Managers –Flow Layout –Border Layout –GridLayout –BoxLayout.

Similar presentations


Presentation on theme: "Chapter 14 Advanced GUI. Topics Mouse Events –MouseListener –MouseMotionListener JPanels Layout Managers –Flow Layout –Border Layout –GridLayout –BoxLayout."— Presentation transcript:

1 Chapter 14 Advanced GUI

2 Topics Mouse Events –MouseListener –MouseMotionListener JPanels Layout Managers –Flow Layout –Border Layout –GridLayout –BoxLayout Event Listeners –ItemEvents –ChangeEvents Other components –JCheckBox –JRadioButton –JComboBox –JList –JScrollPane

3 Handling Mouse Events Mouse events include such user interactions as moving the mouse, dragging the mouse, and clicking the mouse buttons. Java divides mouse-related events into two categories –clicking generates a MouseEvent –moving or dragging the mouse generates a MouseMotionEvent

4 Handling Mouse Events A Ch14TrackMouseFrame object is an event source for 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 { … }

5 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.

6 Handling Mouse Events The mouseClicked method is called every time the left mouse button is clicked (pressed down and released). 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. mouseEntered and mouseExited are called when the mouse over and away from the component generating the events.

7 Mouse Events The getX and getY methods of MouseEvent retrieve the x and y coordinate values of wherever the mouse is clicked. 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.

8 Mouse Buttons When either the right or left mouse button is pressed, the event listener’s 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. –There is also an isAltDown method which can be used to check for the middle mouse button

9 MouseMotionEvents 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.

10 Handling Mouse Events Similar to the mousePressed method, the mouseDragged method is called regardless of which button was down as the mouse was dragged. –The isMetaDown method may again be used here to determine which button was used to drag the mouse.

11 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 –BoxLayout (not in the text)

12 JPanel Class 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.

13 FlowLayout Class 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.

14 FlowLayout We first assign the desired layout manager to the container (in this case, the content pane of a frame) in the frame’s 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.

15 Adding Components to a FlowLayout 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);...

16 FlowLayout Placement of five buttons by using FlowLayout when the frame is first opened and after the frame is resized.

17 BorderLayout The second layout manager is java.awt.BorderLayout. This manager divides the container into five regions: –Center –North –South –East –West

18 BorderLayout 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); Leaving out the region puts the component into the CENTER

19 BorderLayout Placement of five buttons by using BorderLayout when the frame is first opened and after the frame is resized.

20 Partially Filled BorderLayout Placement of two buttons by using BorderLayout. Buttons are placed on the center and east regions.

21 BorderLayout The default of BorderLayout is to have 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));

22 GridLayout The third layout manager is java.awt.GridLayout. This manager places GUI components on a uniform N X M grid. Components are placed from left to right in a row and rows are placed top to bottom.

23 GridLayout 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.

24 GridLayout 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.

25 GridLayout 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. If the number of rows is 0, the number of columns is fixed and the number of rows will be determined by the number of components added.

26 BoxLayout The BoxLayout allows you to place components either in a row or in a column The BoxLayout needs to know who its parent is new BoxLayout( this, BoxLayout.X_AXIS) BoxLayout in in the javax.swing package

27 Box Helper Class The Box class has method that create spacing components –Box.createRigidArea( new Dimension(width, height) creates a fixed spacing –Box.createHorizontalGlue() and Box.createVerticalGlue() create space that expands to fill the leftover space multiple glue components will share the extra space evenly

28 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. 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.

29 Hi-Lo Frame Another sample frame that contains nested panels. Five JPanel objects are used in this frame.

30 Hi-Lo Panel The nested panels and associated layout managers for HiLoDisplay.

31 Tic-Tac-Toe Frame A sample frame that contains nested panels. Four JPanel objects are used in this frame.

32 Tic-Tac-Toe Frame The topmost panel is the content pane of the frame. It has a border layout. –The content pane’s center region contains an instance of Ch14TicTacToePanel named gamePanel. –The content pane’s 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.

33 Tic-Tac-Toe Frame The layout for scorePanel is set to a grid layout with four grids, each occupied by a JLabel object.

34 Effective Use of Nested Panels When we nest panels, it is useful to mark their borders. The BorderFactory class (see Chapter 7) contains many different border formats, such as –titled border –lowered bevel border –line border –etc.

35 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).

36 Tic-Tac-Toe Design There are two ways to approach designing the Tic Tac Toe board of N X 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.

37 Tic-Tac-Toe Design 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 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 origin point of a cell, we can draw a circle or cross by using the drawLine or drawOval method.

38 Tic-Tac-Toe Design 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.

39 Tic-Tac-Toe Design The second approach uses nested panels. We will define two classes –Ch14TicTacToePanel – Ch14TicTacToeCell. An instance of Ch14TicTacToePanel will contain N 2 instances of Ch14TicTacToeCell, each representing a single cell in the board.

40 Tic-Tac-Toe Design 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.

41 Tic-Tac-Toe Design The Ch14TicTacToePanel’s 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.

42 Other GUI Components You are already acquainted with Swing components JButton and JTextField and JTextArea. We will now examine the basic capabilities of some additional Swing components that will be helpful in building your applications.

43 JCheckBox The JCheckBox class is used to represent check-boxes. 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”);

44 JCheckBox Example A frame with four check box buttons and one pushbutton.

45 JCheckBox A JCheckBox object generates both action events and item events. –We generally use and ItemListener with JCheckBoxes –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.

46 ItemListener Interface 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. void ItemStateChanged( ItemEvent evt) { … }

47 JCheckBox 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{... }

48 JRadioButton The JRadioButton class is used to represent a radio button. –RadioButtons work in groups Radio buttons may be selected or deselected –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.

49 JButtonGroup Radio buttons must be added to a button group. JRadioButton buttons[] = new JRadioButton[4]; ButtonGroup group = new ButtonGroup(); JPanel panel = new JPanel(); for (int i=0; i<buttons.length; i++) { button[i] = new JRadioButton(…); group.add( button[i]); panel.add( button[i]); }

50 JRadioButton Example A frame with four radio buttons and one pushbutton.

51 JRadioButton 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. –We usually handle the ActionEvent

52 JComboBox The JComboBox class, like JRadioButton, allows the user to select one of a list of possible choices. –The JComboBox presents the options to the user in a drop-down list. The JComboBox can be editable or not. –An editable JComboBox allows the user to enter his own text –If the JComboBox is not editable, the choices are restricted to those that already exist.

53 JComboBox We can construct a new JComboBox by passing an array of String objects: String[] comboBoxItem = {“Java”, “C++”, “Smalltalk”, “Ada”}; JComboBox comboBox = new JComboBox(comboBoxItem); We can also call the addItem method to add another choice to the combo box

54 JComboBox Example A frame with one combo box (drop-down list) and one pushbutton.

55 JComboBox A JComboBox object generates action and item events. To find out the currently selected item, we call the getSelectedItem method of JComboBox.

56 JList 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); –The constructor's parameter is an array of Objects The toString method determines what is displayed

57 JList Example A frame with one list and one pushbutton.

58 JList With JList, we have an option of specifying one of three selection modes: –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).

59 JList Selection Modes list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); list.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECT ION); list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELE CTION);

60 JList Selecting an item in a JList generates an ActionEvent There are two methods for determining which item(s) is(are) selected –getSelectedValues() returns an array of objects –getSelectedIndices() returns an array of integers containing the positions of the selected items in the list

61 JSlider 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. 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.

62 JSlider A frame with three vertical sliders for setting an RGB value.

63 JSplitPane A JSplitPane is a container (like a JPanel) which has two parts. –the parts can be side-by-side or one above the other JSplitPane content = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT); JSplitPane content = new JSplitPane( JSplitPane.VERTICAL_SPLIT);

64 JSplitPane You can add a component to each side content.setLeftComponent( scroller); content.setRightComponent( JLabel); the divider between the parts can be moved to change the relative sizes of the two parts –the size can be set by the program content.setDividerLocation( 0.5); –the size can be adjusted manually if not disabled

65 etc. JColorChooser –lets the user select a color from a color wheel KeyEvents and the KeyListener interface –for interacting with the keyboard Tool tips –pop-up messages that tell the user what a component is for Browse through documentation for the awt and swing packages


Download ppt "Chapter 14 Advanced GUI. Topics Mouse Events –MouseListener –MouseMotionListener JPanels Layout Managers –Flow Layout –Border Layout –GridLayout –BoxLayout."

Similar presentations


Ads by Google