Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 : Advanced GUI  Mouse Events  JPanels  Layout Managers 

Similar presentations


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

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 : Advanced GUI  Mouse Events  JPanels  Layout Managers  Event Listeners  Other components  JCheckBox  JRadioButton  JComboBox  JList  JSplitPane

2 ©The McGraw-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.  Java divides mouse-related events into two categories clicking generates a MouseEvent moving or dragging the mouse generates a MouseMotionEvent

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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 { … }

4 ©The McGraw-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.

5 ©The McGraw-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 (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.

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

10 ©The McGraw-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 BoxLayout (not in the text)

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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);...

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. BorderLayout  The second layout manager is java.awt.BorderLayout.  This manager divides the container into five regions: Center North South East West

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. BorderLayout  We set the BorderLayout using contentPane.setLayout(new BorderLayout());  And place GUI components with the second argument specifying the region: contentPane.add(button1,BorderLayout.NOR TH); contentPane.add(button1,BorderLayout.SOU TH);  Leaving out the region puts the component into the CENTER

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

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Partially Filled BorderLayout  Placement of two buttons by using BorderLayout. Buttons are placed on the center and east regions.

19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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));

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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) new BoxLayout( this, BoxLayout.Y_AXIS)  BoxLayout in in the javax.swing package

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

26 ©The McGraw-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.  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.

27 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Hi-Lo Frame  A sample frame that contains nested panels. Five JPanel objects are used in this frame.

28 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Hi-Lo Panel  The nested panels and associated layout managers for HiLoDisplay.

29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Tic-Tac-Toe Frame  A sample frame that contains nested panels. Four JPanel objects are used in this frame.

30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

31 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Tic-Tac-Toe Frame  The layout for scorePanel is set to a grid layout with four grids, each occupied by a JLabel object.

32 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Borders for 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.

33 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Borders for 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).

34 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Tic-Tac-Toe Design  Our approach uses nested panels.  The game panel handles the mouse click events Every time the player clicks on a cell, a circle or cross is displayed.  The panel illustrated here does not contain any game logic.  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.

35 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

36 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

37 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

38 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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");

39 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JCheckBox Example  A frame with four check box buttons and one pushbutton.

40 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JCheckBox Events  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.

41 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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) { … }

42 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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{... }

43 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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]); }

45 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JRadioButton Example  A frame with four radio buttons and one pushbutton.

46 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

47 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

48 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

49 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JComboBox Example  A frame with one combo box (drop-down list) and one pushbutton.

50 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JComboBox Events  A JComboBox object generates action and item events.  To find out the currently selected item, we call the getSelectedItem method of JComboBox.

51 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

52 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JList Example  A frame with one list and one pushbutton.

53 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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).

54 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JList Selection Modes list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); list.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELEC TION); list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SEL ECTION);

55 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

56 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

57 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. JSlider  A frame with three vertical sliders for setting an RGB value.

58 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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);

59 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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

60 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 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 "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 : Advanced GUI  Mouse Events  JPanels  Layout Managers "

Similar presentations


Ads by Google