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

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Rectangles moving and responding to the mouse. We want a window with a pile of rectangles in it When we click a rectangle it changes from filled to unfilled.
Introduction to Swing Components Chapter 14. Part of the Java Foundation Classes (JFC) Provides a rich set of GUI components Used to create a Java program.
Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
Graphical User Interfaces
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Graphical User Interfaces, 2D Graphics & Game Programming.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Graphical User Interfaces CS 2110 Spring Ivan Sutherland: “Sketchpad”,
Corresponds with Chapter 12
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 14 : Advanced GUI  Mouse Events  JPanels  Layout Managers 
Event Handling Events and Listeners Timers and Animation.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 14 Advanced GUI. Topics Mouse Events –MouseListener –MouseMotionListener JPanels Layout Managers –Flow Layout –Border Layout –GridLayout –BoxLayout.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
GUI and event-driven programming An introduction.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Advanced Java and Android Programming Day 1: Introduction to GUI Programming Intro to GUI Programming1.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Basics of GUI Programming Chapter 11 and Chapter 22.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-3 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 7 A First Look at GUI Applications Layout Managers.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Graphical User Interface (pronounced "gooey")
Chapter 13: Advanced GUIs and Graphics
Creating Graphical User Interfaces
Graphical User Interface
Chapter 7-3 (Book Chapter 14)
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Chapter 14 Advanced GUI ©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. ©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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

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

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

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

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

14.1 Handling Mouse Events 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

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

14.1 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; } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.1 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() ) { //don’t 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 ) { } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

14.3 Effective Use of Nested Panels The topmost panel in Fig. 14.5 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.3 Effective Use of Nested Panels 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

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

14.3 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); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.3 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( )); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.3 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:")); 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 ); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

14.3 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(); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.3 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); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

14.3 Effective Use of Nested Panels There are two ways to approach designing the Tic Tac Toe board of N × N = N2 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

14.3 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 N2 instances of Ch14TicTacToeCell, each representing a single cell in the board. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

14.3 Effective Use of Nested Panels The Ch14TicTacToePanel’s main tasks are to handle the layout of N2 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

14.4 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”); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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