338
1 1992-2007 Pearson Education, Inc. All rights rese 1 2 GUI Components: Part 1

1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

Embed Size (px)

Citation preview

Page 1: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

1

1992-2007 Pearson Education, Inc. All rights reserved.

1212GUI Components:

Part 1

Page 2: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

2

1992-2007 Pearson Education, Inc. All rights reserved.

OBJECTIVES

In this chapter you will learn: The design principles of graphical user interfaces

(GUIs). To build GUIs and handle events generated by

user interactions with GUIs. To understand the packages containing GUI

components, event-handling classes and interfaces.

To create and manipulate buttons, labels, lists, text fields and panels.

To handle mouse events and keyboard events. To use layout managers to arrange GUI

components

Page 3: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

3

1992-2007 Pearson Education, Inc. All rights reserved.

11.1 Introduction

11.2 Simple GUI-Based Input/Output with JOptionPane 11.3 Overview of Swing Components

11.4 Displaying Text and Images in a Window

11.5 Text Fields and an Introduction to Event Handling with Nested Classes

11.6 Common GUI Event Types and Listener Interfaces

11.7 How Event Handling Works

11.8 JButton

11.9 Buttons That Maintain State

11.9.1 JCheckBox

11.9.2 JRadioButton

11.10 JComboBox and Using an Anonymous Inner Class for Event Handling

Page 4: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

4

1992-2007 Pearson Education, Inc. All rights reserved.

11.11 JList

11.12 Multiple-Selection Lists

11.13 Mouse Event Handling

11.14 Adapter Classes

11.15 JPanel Sublcass for Drawing with the Mouse

11.16 Key-Event Handling

11.17 Layout Managers

11.17.1 FlowLayout

11.17.2 BorderLayout

11.17.3 GridLayout

11.18 Using Panels to Manage More Complex Layouts

11.19 JTextArea

11.20 Wrap-Up

Page 5: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

5

1992-2007 Pearson Education, Inc. All rights reserved.

11.1 Introduction

• Graphical user interface (GUI)– Presents a user-friendly mechanism for interacting with an

application

– Often contains title bar, menu bar containing menus, buttons and combo boxes

– Built from GUI components

Page 6: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

6

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.1 | Internet Explorer window with GUI components.

button menus title bar menu bar combo box

scrollbars

Page 7: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

7

1992-2007 Pearson Education, Inc. All rights reserved.

11.2 Simple GUI-Based Input/Output with JOptionPane

• Dialog boxes– Used by applications to interact with the user

– Provided by Java’s JOptionPane class• Contains input dialogs and message dialogs

• invoking static JOptionPane methods

Page 8: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

8

1992-2007 Pearson Education, Inc. All rights reserved.

Example: JOptionPane

import javax.swing.JOptionPane; // program uses JOptionPane

public class Addition { public static void main( String args[]) {// obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );

// convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstNumber );

int number2 = Integer.parseInt( secondNumber );

int sum = number1 + number2; // add numbers

Page 9: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

9

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// display result in a JOptionPane message dialog

JOptionPane.showMessageDialog(null,"The sum is "

+ sum,"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); } // end method main} // end class Addition

Page 10: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

10

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Addition.java

(1 of 2)

1 // Fig. 11.2: Addition.java

2 // Addition program that uses JOptionPane for input and output.

3 import javax.swing.JOptionPane; // program uses JOptionPane

4

5 public class Addition

6 {

7 public static void main( String args[] )

8 {

9 // obtain user input from JOptionPane input dialogs

10 String firstNumber =

11 JOptionPane.showInputDialog( "Enter first integer" );

12 String secondNumber =

13 JOptionPane.showInputDialog( "Enter second integer" );

14

15 // convert String inputs to int values for use in a calculation

16 int number1 = Integer.parseInt( firstNumber );

17 int number2 = Integer.parseInt( secondNumber );

18

19 int sum = number1 + number2; // add numbers

20

21 // display result in a JOptionPane message dialog

22 JOptionPane.showMessageDialog( null, "The sum is " + sum,

23 "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );

24 } // end method main

25 } // end class Addition

Page 11: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

11

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Addition.java

(2 of 2)

Input dialog displayed by lines 10–11

Input dialog displayed by lines 12–13

Message dialog displayed by lines 22–23

Text field in which the user types avalue

Prompt to the user

When the user clicks OK, showInputDialog

returns to the program the 100 typed by the

user as a String. The program must convert the String to an int

title bar

When the user clicks OK, the message dialog is dismissed

(removed from the screen)

Page 12: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

12

1992-2007 Pearson Education, Inc. All rights reserved.

11.2 Simple GUI-Based Input/Output with JOptionPane

• Input dialogs– return String

• Converting String to int values– Integer class static parseInt method– converts its String argument to an int value

• Message Dialogs– JOptionPane’s static method showMessageDialog

• 1th argumenet – possition – null: center of screen• 2th argument - message to be display• 3th argument – String on the Title bar of the dialog box• 4th argument – constants:icon types

Page 13: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

13

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.3 | JOptionPane static constants for message dialogs.

Message dialog type Icon Description

ERROR_MESSAGE

A dialog that indicates an error to the user.

INFORMATION_MESSAGE

A dialog with an informational message to the user.

WARNING_MESSAGE

A dialog warning the user of a potential problem.

QUESTION_MESSAGE

A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button.

PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.

Page 14: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

14

1992-2007 Pearson Education, Inc. All rights reserved.

11.3 Overview of Swing Components

• Swing GUI components– Declared in package javax.swing

– Most are pure Java components

– Part of the Java Foundation Classes (JFC)

Page 15: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

15

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.4 | Some basic GUI components.

Component Description

JLabel Displays uneditable text or icons.

JTextField Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text.

JButton Triggers an event when clicked with the mouse.

JCheckBox Specifies an option that can be selected or not selected.

JComboBox Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box.

JList Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected.

JPanel Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics.

Page 16: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

16

1992-2007 Pearson Education, Inc. All rights reserved.

Swing vs. AWT

• Abstract Window Toolkit (AWT)– Precursor to Swing

– Declared in package java.awt

– Does not provide consistent, cross-platform look-and-feel

Page 17: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

17

1992-2007 Pearson Education, Inc. All rights reserved.

Portability Tip 11.1

Swing components are implemented in Java, so they are more portable and flexible than the original Java GUI components from package java.awt, which were based on the GUI components of the underlying platform. For this reason, Swing GUI components are generally preferred.

Page 18: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

18

1992-2007 Pearson Education, Inc. All rights reserved.

Lightweight vs. Heavyweight GUI Components

• Lightweight components– Not tied directly to GUI components supported by

underlying platform

• Heavyweight components– Tied directly to the local platform

– AWT components

– Some Swing components

Page 19: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

19

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.4

The look and feel of a GUI defined with heavyweight GUI components from package java.awt may vary across platforms. Because heavyweight components are tied to the local-platform GUI, the look and feel varies from platform to platform.

Page 20: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

20

1992-2007 Pearson Education, Inc. All rights reserved.

Superclasses of Swing’s Lightweight GUI Components

• Class Component (package java.awt)– Subclass of Object

– Declares many behaviors and attributes common to GUI components

• Class Container (package java.awt)– Subclass of Component

– Organizes Components

• Class JComponent (package javax.swing)– Subclass of Container

– Superclass of all lightweight Swing components

Page 21: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

21

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.1

Study the attributes and behaviors of the classes in the class hierarchy of Fig. 11.5. These classes declare the features that are common to most Swing components.

Page 22: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

22

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.5 | Common superclasses of many of the Swing components.

Page 23: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

23

1992-2007 Pearson Education, Inc. All rights reserved.

Superclasses of Swing’s Lightweight GUI Components

• Common lightweight component features– Pluggable look-and-feel to customize the appearance of

components

– Shortcut keys (called mnemonics)

– Common event-handling capabilities

– Brief description of component’s purpose (called tool tips)

– Support for localization

Page 24: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

24

1992-2007 Pearson Education, Inc. All rights reserved.

11.4 Displaying Text and Images in a Window

• Class JFrame– Most windows are an instance or subclass of this class

– Provides title bar

– Provides buttons to minimize, maximize and close the application

Page 25: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

25

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;public class FrameTest { public static void main(String args[]) {

JFrame firstFrame = new JFrame("First Frame"); firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstFrame.setSize(200, 300);

firstFrame.setVisible(true);

} // end main} // end class FrameTest

Page 26: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

26

1992-2007 Pearson Education, Inc. All rights reserved.

Output an empty JFrame

Page 27: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

27

1992-2007 Pearson Education, Inc. All rights reserved.

JFrame firstFrame = new JFrame("First Frame");

•firstFrame: reference of type JFrame– in javax.swing package

• create JFrame object by setting its title

• JFrame indirect subclass of java.awt.Window– attributes and behavior of a window:

• Title bar at the top

• buttoms for closing, minimizing ...

Page 28: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

28

1992-2007 Pearson Education, Inc. All rights reserved.

Creating and Displaying a LabelFrame Window

• Other JFrame methods– setDefaultCloseOperation

• Dictates how the application reacts when the user clicks the close button

– setSize• Specifies the width and height of the window

– setVisible• Determines whether the window is displayed (true) or not

(false)

Page 29: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

29

1992-2007 Pearson Education, Inc. All rights reserved.

Labeling GUI Components

• Label– Text instructions or information stating the purpose of

each component

– Created with class JLabel

Page 30: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

30

1992-2007 Pearson Education, Inc. All rights reserved.

General Framework for GUI Applications

• A subclass of JFrame– illustrate new GUI concepts

• An application class– main creates and displays the applicatins window

Page 31: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

31

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.5

Text in a JLabel normally uses sentence-style capitalization.

Page 32: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

32

1992-2007 Pearson Education, Inc. All rights reserved.

Adding a label to the Frame class Label1

import javax.swing.*;import java.awt.*;public class Label0 {public static void main(String[] args){ LabelFrame firstLabel = new LabelFrame("Frame with Label");

firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

firstLabel.setSize(200, 300);firstLabel.setVisible(true);

} // end main} // end class Label1

Page 33: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

33

1992-2007 Pearson Education, Inc. All rights reserved.

class LabelFrame extends JFrame {// creates a JLabel reference private JLabel label1; public LabelFrame(String title) { super(title); // send the title to JFrame’s consturctor

// set labout setLayout(new FlowLayout());

// create a new JLabel refered by label1 label1 = new JLabel("I am a label"); add(label1); // add to the frame } // end constructor} // end classLabelFrame

Page 34: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

34

1992-2007 Pearson Education, Inc. All rights reserved.

Class Label0 – test or application class

LabelFrame firstLabel = new LabelFrame("Frame with Label");

• LabelFrame extends from JFrame• firstLabel: is a reference to a LabelFrame type object• Create the object with its title• use methods of JFrame to set

– close operation– size– visiblilility

• of the firstLabel

Page 35: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

35

1992-2007 Pearson Education, Inc. All rights reserved.

Class LabelFrame - extends from JFrame

– hold the components – label1

– set the layout

– create the labels label1

– add to the JFrame

Page 36: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

36

1992-2007 Pearson Education, Inc. All rights reserved.

Another approach – not prefered

• Create a JFrame object

send title to its constrcutor

set the properties

create a JLabel reference

set layout on JFrame

create the object label1

add label1 to jlabelFrame

Page 37: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

37

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;import java.awt.*;public class Label0 {public static void main(String[] args) { JFrame firstLabel = new JFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstLabel.setSize(200, 300); firstLabel.setVisible(true);

JLabel label1; // a JLabel type varible firstLabel. setLayout(new FlowLayout());// create a new JLabel refered by label1 label1 = new JLabel("I am a label"); firstLabel.add(label1); // add to the frame} // end main

} // end class Label1

Page 38: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

38

1992-2007 Pearson Education, Inc. All rights reserved.

Adding a labels to the Frame class Label1

import javax.swing.*;

import java.awt.*;

public class Label1 {

public static void main(String[] args)

{

LabelFrame firstLabel = new LabelFrame("Frame with Label");

firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

firstLabel.setSize(200, 300);

firstLabel.setVisible(true);

} // end main

} // end class Label1

Page 39: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

39

1992-2007 Pearson Education, Inc. All rights reserved.

Explanations

LabelFrame firstLabel = new LabelFrame("Frame with Label");

• LabelFrame extends from JFrame

• firstLabel: is a reference to a LabelFrame type object

• Create the object with its title

• use methods of JFrame to set– close operation

– size

– visiblilility

• of the firstLabel

Page 40: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

40

1992-2007 Pearson Education, Inc. All rights reserved.

class Label1Frame

• extends from JFrame

• hold the components – 3 JLabel s

• set the layout

• create the labels label1 and label2– seting a tooltip for label2 – toolTipSet method

• add to the JFrame

Page 41: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

41

1992-2007 Pearson Education, Inc. All rights reserved.

class Label1Freme

class LabelFrame extends JFrame {

// creates three JLabel references private JLabel label1; private JLabel label2;private JLabel label3;

public LabelFrame(String title) {super(title); // send the title to JFrame’s

consturctor// set labout

setLayout(new FlowLayout());

Page 42: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

42

1992-2007 Pearson Education, Inc. All rights reserved.

// create a new JLabel refered by label1 label1 = new JLabel("I am a label");

add(label1); // add to the frame

// create a new JLabel refered by label2 label2 = new JLabel("second label");label2.setToolTipText("tooltip of scond label");

// set a tooltip to label2 invoking setToolTip methodadd(label2);

// add to the frame

Page 43: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

43

1992-2007 Pearson Education, Inc. All rights reserved.

// create a new JLabel refered by label3 label3 = new JLabel();

label3.setText("label 3");label3.setToolTipText("tool tip text 3");

label3.setHorizontalTextPosition(SwingConstants.CENTER);

label3.setVerticalTextPosition(SwingConstants.BOTTOM);

add(label3);;

} // end constructor} // end class LabelFrame

Page 44: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

44

1992-2007 Pearson Education, Inc. All rights reserved.

Specifying the Layout

• Laying out containers– Determines where components are placed in the container

• Window creatred with JFrame

– Done in Java with layout managers• One of which is class FlowLayout

– Set with the setLayout method• İnherited indirectly form class Container

• setLayout(new FlowLayout());– A FlowLayout object is created without a reference and send to

setLayout method as an argument

– The parameter lacal variable is the refernce – LayoutManager interface

Page 45: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

45

1992-2007 Pearson Education, Inc. All rights reserved.

output of program

Page 46: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

46

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LabelFrame.java

(1 of 2)

1 // Fig. 11.6: LabelFrame.java

2 // Demonstrating the JLabel class.

3 import java.awt.FlowLayout; // specifies how components are arranged

4 import javax.swing.JFrame; // provides basic window features

5 import javax.swing.JLabel; // displays text and images

6 import javax.swing.SwingConstants; // common constants used with Swing

7 import javax.swing.Icon; // interface used to manipulate images

8 import javax.swing.ImageIcon; // loads images

9

10 public class LabelFrame extends JFrame

11 {

12 private JLabel label1; // JLabel with just text

13 private JLabel label2; // JLabel constructed with text and icon

14 private JLabel label3; // JLabel with added text and icon

15

16 // LabelFrame constructor adds JLabels to JFrame

Page 47: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

47

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LabelFrame.java

(1 of 2)

1 // Fig. 11.6: LabelFrame.java

16 // LabelFrame constructor adds JLabels to JFrame

17 public LabelFrame()

18 {

19 super( "Testing JLabel" );

20 setLayout( new FlowLayout() ); // set frame layout

21

22 // JLabel constructor with a string argument

23 label1 = new JLabel( "Label with text" );

24 label1.setToolTipText( "This is label1" );

25 add( label1 ); // add label1 to JFrame

26

Page 48: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

48

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LabelFrame.java

(2 of 2)27 // JLabel constructor with string, Icon and alignment arguments

28 Icon bug = new ImageIcon( getClass().getResource( "bug1.gif" ) );

29 label2 = new JLabel( "Label with text and icon", bug,

30 SwingConstants.LEFT );

31 label2.setToolTipText( "This is label2" );

32 add( label2 ); // add label2 to JFrame

33

34 label3 = new JLabel(); // JLabel constructor no arguments

35 label3.setText( "Label with icon and text at bottom" );

36 label3.setIcon( bug ); // add icon to JLabel

37 label3.setHorizontalTextPosition( SwingConstants.CENTER );

38 label3.setVerticalTextPosition( SwingConstants.BOTTOM );

39 label3.setToolTipText( "This is label3" );

40 add( label3 ); // add label3 to JFrame

41 } // end LabelFrame constructor

42 } // end class LabelFrame

Page 49: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

49

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LabelTest.java

1 // Fig. 11.7: LabelTest.java

2 // Testing LabelFrame.

3 import javax.swing.JFrame;

5 public class LabelTest

6 {

7 public static void main( String args[] )

8 { 9 LabelFrame labelFrame = new LabelFrame(); // create LabelFrame 10 labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 labelFrame.setSize( 275, 180 ); // set frame size

12 labelFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class LabelTest

Page 50: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

50

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LabelTest.java

Page 51: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

51

1992-2007 Pearson Education, Inc. All rights reserved.

Creating and Attaching label1

• Method setToolTipText of class JComponent

– Specifies the tool tip

• Method add of class Container– Adds a component to a container

Page 52: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

52

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.1

If you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.

Page 53: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

53

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.6

Use tool tips to add descriptive text to your GUI components. This text helps the user determine the GUI component’s purpose in the user interface.

Page 54: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

54

1992-2007 Pearson Education, Inc. All rights reserved.

Creating and Attaching label2

• Interface Icon– Can be added to a JLabel with the setIcon method

– Implemented by class ImageIcon

• Interface SwingConstants– Declares a set of common integer constants such as those

used to set the alignment of components

– Can be used with methods setHorizontalAlignment and setVerticalAlignment

Page 55: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

55

1992-2007 Pearson Education, Inc. All rights reserved.

Creating and Attaching label3

• Other JLabel methods– getText and setText

• For setting and retrieving the text of a label

– getIcon and setIcon• For setting and retrieving the icon displayed in the label

– getHorizontalTextPosition and setHorizontalTextPosition

• For setting and retrieving the horizontal position of the text displayed in the label

Page 56: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

56

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.8 | Some basic GUI components.

Constant

Description

Horizontal-position constants

SwingConstants.LEFT Place text on the left. SwingConstants.CENTER Place text in the center. SwingConstants.RIGHT Place text on the right.

Vertical-position constants

SwingConstants.TOP Place text at the top. SwingConstants.CENTER Place text in the center. SwingConstants.BOTTOM Place text at the bottom.

Page 57: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

57

1992-2007 Pearson Education, Inc. All rights reserved.

11.5 Text Fields and an Introduction to Event Handling with Nested Classes

• GUIs are event-driven– A user interaction creates an event

• Common events are:

– clicking a button

– typing in a text field

– selecting an item from a menu

– closing and window

– moving the mouse

– The event causes a call to a method called an event handler

Page 58: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

58

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class Button0 {

public static void main(String[] args) { ButtonFrame jButtonFrame = new ButtonFrame("Title"); jButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jButtonFrame.setLocationRelativeTo(null); jButtonFrame.setSize(200, 400); jButtonFrame.setVisible(true);}

}

Page 59: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

59

1992-2007 Pearson Education, Inc. All rights reserved.

class ButtonFrame extends JFrame {

private JButton button;

public ButtonFrame(String title) { super(title); setLayout(new FlowLayout()); button = new JButton("I am a Button"); add(button);

ButtonHandler handler = new ButtonHandler(); button.addActionListener(handler);

} // end constructor

Page 60: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

60

1992-2007 Pearson Education, Inc. All rights reserved.

private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null,"You clicked me");

} // end actionPerformed} // end inner class

} // end class ButtonFrame

Page 61: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

61

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class Button1 {

public static void main(String[] args){

JFrame jButton = new JFrame("Title");jButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jButton.setLocationRelativeTo(null);jButton.setSize(200, 400);jButton.setVisible(true);

jButton.setLayout(new FlowLayout());

Page 62: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

62

1992-2007 Pearson Education, Inc. All rights reserved.

JButton button;

button = new JButton("I am a Button");

jButton.add(button);

ButtonHandler handler = new ButtonHandler();

button.addActionListener(handler);

} // end main

} // end class Button1

Page 63: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

63

1992-2007 Pearson Education, Inc. All rights reserved.

class ButtonHandler implements ActionListener {public void actionPerformed(ActionEvent e){

JOptionPane.showMessageDialog(null,"You clicked me");

} // end of actionPerformed} // end of class

Page 64: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

64

1992-2007 Pearson Education, Inc. All rights reserved.

output of the program

Page 65: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

65

1992-2007 Pearson Education, Inc. All rights reserved.

11.5 Text Fields and an Introduction to Event Handling with Nested Classes

• Class JTextComponent– Superclass of JTextField

• Superclass of JPasswordField

– Adds echo character to hide text input in component

– Allows user to enter text in the component when component has the application’s focus

Page 66: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

66

1992-2007 Pearson Education, Inc. All rights reserved.

11.5 Text Fields and an Introduction to Event Handling with Nested Classes

import javax.swing.*;import java.awt.*;

public class Text0 {public static void main(String[] args) { JText0 jTextFrame = new JText0("TextField"); jTextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jTextFrame.setSize(200, 400); jTextFrame.setVisible(true);} end main

} end class Text0

Page 67: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

67

1992-2007 Pearson Education, Inc. All rights reserved.

Program continued

class JText0 extends JFrame {

private JTextField textField1;

public JText0(String title) { super(title);

setLayout(new FlowLayout());

textField1 = new JTextField(10); add(textField1);

TextHandler handler = new TextHandler(); textField1.addActionListener(handler);

} // end constructor JText0// the class has not ended

Page 68: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

68

1992-2007 Pearson Education, Inc. All rights reserved.

Program continued

private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) {

String string = String.format( “text field:%s”,e.getActionCommand());

JOptionPane.showMessageDialog(null,string);

} // end method actionPerformed} // end innter class TextHandler

} // end class JText0

Page 69: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

69

1992-2007 Pearson Education, Inc. All rights reserved.

Another version using getText method

private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { // useing the getText method

String string = String.format(“text field:%s”,textField1.getText());

JOptionPane.showMessageDialog(null,string);

} // end method actionPerformed} // end innter class TextHandler

} // end class JText0

Page 70: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

70

1992-2007 Pearson Education, Inc. All rights reserved.

The output:

Page 71: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

71

1992-2007 Pearson Education, Inc. All rights reserved.

11.5 Text Fields and an Introduction to Event Handling with Nested Classes

import javax.swing.*;import java.awt.*;

public class Text0 {public static void main(String[] args){

JText0 jTextFrame = new JText0("TextField");

jTextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jTextFrame.setSize(200, 400);jTextFrame.setVisible(true);

}}

Page 72: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

72

1992-2007 Pearson Education, Inc. All rights reserved.

class JText0 extends JFrame {

private JTextField textField1;private JTextField textField2;

public JText0(String title) {super(title);

setLayout(new FlowLayout());

textField1 = new JTextField(10);textField2 = new JTextField("Enter text");

add(textField1);add(textField2);

TextHandler handler = new TextHandler();textField1.addActionListener(handler);textField2.addActionListener(handler);

} // end constructor JText0

Page 73: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

73

1992-2007 Pearson Education, Inc. All rights reserved.

Another version

private class TextHandler implements ActionListener {public void actionPerformed(ActionEvent e){ if(e.getSource()==textField1)

String string = String.format(“text field:%s”, textField1.getText ()); else String string = String.format(“text field:%s”, textField2.getText ()); JOptionPane.showMessageDialog(null,string);

} // end method actionPerformed

} // end innter class TextHandler} // end class JText0

Page 74: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

74

1992-2007 Pearson Education, Inc. All rights reserved.

Page 75: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

75

1992-2007 Pearson Education, Inc. All rights reserved.

Text and Pasword Fields Book’s example

import java.awt.*;import javax.swing.*;

public class TextFieldTest { public static void main( String args[] ){

TextFieldFrame textFieldFrame = new TextFieldFrame(); textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); textFieldFrame.setSize( 325, 100 ); textFieldFrame.setVisible( true );

} // end main} // end class TextFieldTest

Page 76: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

76

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

class TextFieldFrame extends JFrame {// text field with set size private JTextField textField1; // text field constructed with text private JTextField textField2; // text field with text and size private JTextField textField3;

// password field with text private JPasswordField passwordField;

Page 77: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

77

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// TextFieldFrame constructor adds JTextFields to JFrame public TextFieldFrame() { super( "Testing JTextField and JPasswordField");

// set frame layout setLayout( new FlowLayout() );

// construct textfield with 10 columns textField1 = new JTextField( 10 ); // add textField1 to JFrame add( textField1 );

// construct textfield with default text textField2 = new JTextField( "Enter text here" ); // add textField2 to JFrame add( textField2 );

Page 78: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

78

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// construct textfield with default text and 21 columns

textField3 = new JTextField( "Uneditable text field", 21);

// disable editing textField3.setEditable( false ); // add textField3 to JFrame add( textField3 );

// construct passwordfield with default text passwordField = new JPasswordField( "Hidden text"); // add passwordField to JFrame add( passwordField );

Page 79: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

79

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler );

textField2.addActionListener( handler );

textField3.addActionListener( handler );

passwordField.addActionListener( handler );

} // end TextFieldFrame constructor

Page 80: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

80

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// private inner class for event handling private class TextFieldHandler implements ActionListener { // process text field events public void actionPerformed( ActionEvent event ) { String string = ""; // declare string to display

// user pressed Enter in JTextField textField1 if ( event.getSource() == textField1 ) string = String.format( "textField1: %s", event.getActionCommand() );

// user pressed Enter in JTextField textField2 else if ( event.getSource() == textField2 ) string = String.format( "textField2: %s", event.getActionCommand() );

Page 81: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

81

1992-2007 Pearson Education, Inc. All rights reserved.

Example (cont.)

// user pressed Enter in JTextField passwordField

else if ( event.getSource() == passwordField )

string = String.format( "passwordField: %s",

new String( passwordField.getPassword() ) );

// display JTextField content JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end private inner class TextFieldHandler} // end class TextFieldFrame

Page 82: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

82

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextFieldTest.java

(1 of 2)

Page 83: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

83

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextFieldTest.java

(2 of 2)

Page 84: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

84

1992-2007 Pearson Education, Inc. All rights reserved.

Steps Required to Set Up Event Handling for a GUI Component

• Several coding steps are required for an application to respond to events

– Create a class for the event handler

– Implement an appropriate event-listener interface

– Register the event handler

Page 85: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

85

1992-2007 Pearson Education, Inc. All rights reserved.

Using a Nested Class to Implement an Event Handler

• Top-level classes– Not declared within another class

• Nested classes– Declared within another class

– Non-static nested classes are called inner classes• Frequently used for event handling

Page 86: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

86

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.2

An inner class is allowed to directly access its top-level class’s variables and methods, even if they are private.

Page 87: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

87

1992-2007 Pearson Education, Inc. All rights reserved.

Using a Nested Class to Implement an Event Handler

•JTextFields and JPasswordFields– Pressing enter within either of these fields causes an ActionEvent

• Processed by objects that implement the ActionListener interface

Page 88: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

88

1992-2007 Pearson Education, Inc. All rights reserved.

Registering the Event Handler for Each Text Field

• Registering an event handler– Call method addActionListener to register an ActionListener object

– ActionListener listens for events on the object

Page 89: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

89

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.3

The event listener for an event must implement the appropriate event-listener interface.

Page 90: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

90

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.2

Forgetting to register an event-handler object for a particular GUI component’s event type causes events of that type to be ignored.

Page 91: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

91

1992-2007 Pearson Education, Inc. All rights reserved.

Details of Class TextFieldHandler’s actionPerformed Method

• Event source– Component from which event originates

– Can be determined using method getSource

– Text from a JTextField can be acquired using getActionCommand

– Text from a JPasswordField can be acquired using getPassword

Page 92: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

92

1992-2007 Pearson Education, Inc. All rights reserved.

11.6 Common GUI Event Types and Listener Interfaces

•when the user presses enter in a textFieald

– information is stored in ActionEvent object

•many different events occur when the user interracts with the GUI

– information is stored in different objects whose classes inherit from AWTEvent

Page 93: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

93

1992-2007 Pearson Education, Inc. All rights reserved.

11.6 Common GUI Event Types and Listener Interfaces

• Event types– All are subclasses of AWTEvent

– Some declared in package java.awt.event

– Those specific to Swing components declared in javax.swing.event

Page 94: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

94

1992-2007 Pearson Education, Inc. All rights reserved.

11.6 Common GUI Event Types and Listener Interfaces

•event source

•event object

•event listener

Page 95: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

95

1992-2007 Pearson Education, Inc. All rights reserved.

11.6 Common GUI Event Types and Listener Interfaces

• Delegation event model– Event source is the component with which user interacts

– Event object is created and contains information about the event that happened

• any event specific information

• e.g.: text entered in a text box

– Event listener is notified when an event happens• one of its methods executes when an event occurs

• get information about the event from the event object

• what to do when an event occurs coded in event listener that get infromation from event object

Page 96: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

96

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.11 | Some event classes of package java.awt.event.

Page 97: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

97

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.12 | Some common event-listener interfaces of package java.awt.event.

Page 98: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

98

1992-2007 Pearson Education, Inc. All rights reserved.

Event listeners

• a corresponding listener for each event object

• interface so all of its method must be implemented in concrete classes sooner or later

– mostly in package java.awt.event

– soma additional in javax.swing.event

• each contains one or more methods– e.g.: when the user press Enter in a text field

– the listeners actionPerformed method is called

Page 99: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

99

1992-2007 Pearson Education, Inc. All rights reserved.

11.7 How Event Handling Works

• Remaining questions– How did the event handler get registered?

– How does the GUI component know to call actionPerformed rather than some other event-handling method?

Page 100: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

100

1992-2007 Pearson Education, Inc. All rights reserved.

Registering Events

• Every JComponent has instance variable listenerList

– Object of type EventListenerList

– Maintains references to all its registered listeners

Page 101: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

101

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.13 | Event registration for JTextField textField1 .

Page 102: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

102

1992-2007 Pearson Education, Inc. All rights reserved.

Event-Handler Invocation

• Events are dispatched to only the event listeners that match the event type

– Events have a unique event ID specifying the event type

•ActionEvents are handled by Actionisteners and

•MouseEvents are handled by MouseListeners and MouseMotionsListeners

•KeyEvents are handled by KeyListeners

• Dispatching: – the process by which GUI component calls an event handling

method on each of its registered listeners

Page 103: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

103

1992-2007 Pearson Education, Inc. All rights reserved.

Event-Handler Invocation

• For an ActionEvent the event is dispatched to every registered listeners actionPerformed method (the only method)

• For a MouseEvent the event is dispatched to every registered MouseListner or MouseMotion listener depending on the event occur

– Which method to call is determined by the event ID

• Just register an event handler for the particular event type

– Appropriate method of the event handler is called when the envet occurs

Page 104: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

104

1992-2007 Pearson Education, Inc. All rights reserved.

11.8 JButton

• Button– Component user clicks to trigger a specific action

– Can be command button, check box, toggle button or radio button

– Button types are subclasses of class AbstractButton

Page 105: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

105

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.7

Buttons typically use book-title capitalization.

Page 106: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

106

1992-2007 Pearson Education, Inc. All rights reserved.

11.8 JButton

• Command button– Generates an ActionEvent when it is clicked

– Created with class JButton

– Text on the face of the button is called button label

Page 107: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

107

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.8

Having more than one JButton with the same label makes the JButtons ambiguous to the user. Provide a unique label for each button.

Page 108: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

108

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.14 | Swing button hierarchy.

Page 109: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

109

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ButtonFrame.java

(1 of 2)

3 import java.awt.FlowLayout; 4 import java.awt.event.ActionListener;

5 import java.awt.event.ActionEvent;

6 import javax.swing.JFrame;

7 import javax.swing.JButton;

8 import javax.swing.Icon;

9 import javax.swing.ImageIcon;

10 import javax.swing.JOptionPane;

11

12 public class ButtonFrame extends JFrame

13 {

14 private JButton plainJButton; // button with just text

15 private JButton fancyJButton; // button with icons

16

17 // ButtonFrame adds JButtons to JFrame

18 public ButtonFrame()

19 {

20 super( "Testing Buttons" );

21 setLayout( new FlowLayout() ); // set frame layout

22

23 plainJButton = new JButton( "Plain Button" ); // button with text

24 add( plainJButton ); // add plainJButton to JFrame

Page 110: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

110

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ButtonFrame.java

(1 of 2)

26 Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) );

27 Icon bug2 = new ImageIcon( getClass().getResource( "bug2.gif" ) );

28 fancyJButton = new JButton( "Fancy Button", bug1 ); // set image

29 fancyJButton.setRolloverIcon( bug2 ); // set rollover image

30 add( fancyJButton ); // add fancyJButton to JFrame

32 // create new ButtonHandler for button event handling

33 ButtonHandler handler = new ButtonHandler();

34 fancyJButton.addActionListener( handler );

35 plainJButton.addActionListener( handler );

36 } // end ButtonFrame constructor

37

38 // inner class for button event handling

39 private class ButtonHandler implements ActionListener

40 {

41 // handle button event

42 public void actionPerformed( ActionEvent event )

43 { 44 JOptionPane.showMessageDialog( ButtonFrame.this, String.format( 45 "You pressed: %s", event.getActionCommand() ) );

46 } // end method actionPerformed

47 } // end private inner class ButtonHandler

48 } // end class ButtonFrame

Page 111: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

111

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ButtonTest.java

(1 of 2)

3 import javax.swing.JFrame;

4

5 public class ButtonTest

6 {

7 public static void main( String args[] )

8 {

9 ButtonFrame buttonFrame = new ButtonFrame(); // create ButtonFrame

10 buttonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 buttonFrame.setSize( 275, 110 ); // set frame size

12 buttonFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class ButtonTest

Page 112: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

112

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ButtonTest.java

(1 of 2)

Page 113: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

113

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ButtonTest.java

(2 of 2)

Page 114: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

114

1992-2007 Pearson Education, Inc. All rights reserved.

11.8 JButton

•JButtons can have a rollover icon– Appears when mouse is positioned over a button

– Added to a JButton with method setRolloverIcon

Page 115: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

115

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.9

 Because class AbstractButton supports displaying text and images on a button, all subclasses of AbstractButton also support displaying text and images.

Page 116: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

116

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.10

Using rollover icons for JButtons provides users with visual feedback indicating that when they click the mouse while the cursor is positioned over the button, an action will occur.

Page 117: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

117

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.4

When used in an inner class, keyword this refers to the current inner-class object being manipulated. An inner-class method can use its outer-class object’s this by preceding this with the outer-class name and a dot, as in ButtonFrame.this. JOptionPane.showMessageDialog( ButtonFrame.this,

String.format( "You pressed: %s",

event.getActionCommand() ) );

Page 118: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

118

1992-2007 Pearson Education, Inc. All rights reserved.

11.9 Buttons That Maintain State

• State buttons– Swing contains three types of state buttons

– JToggleButton, JCheckBox and JRadioButton

– JCheckBox and JRadioButton are subclasses of JToggleButton

Page 119: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

119

1992-2007 Pearson Education, Inc. All rights reserved.

11.9.1 JCheckBox

•JCheckBox– Contains a check box label that appears to right of check

box by default

– Generates an ItemEvent when it is clicked• ItemEvents are handled by an ItemListener• Passed to method itemStateChanged

– Method isSelected returns whether check box is selected (true) or not (false)

Page 120: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

120

1992-2007 Pearson Education, Inc. All rights reserved.

Test class

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class CheckBox0 {

public static void main(String[] args) { CheckBoxFrame0 checkBoxFrame0 = new CheckBoxFrame0();

checkBoxFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); checkBoxFrame0.setSize(400, 400); checkBoxFrame0.setVisible(true); } // end mehod main

} endd class CheckBox0

Page 121: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

121

1992-2007 Pearson Education, Inc. All rights reserved.

class CheckBoxFrame0 extends JFrame {

private JLabel priceLabel;private JCheckBox cheeseCheckBox;private JCheckBox salamiCheckBox;

private int pricePlane = 10;private int priceCheese = 5;private int priceSalami = 7;private int totalPrice = pricePlane;private String priceString = "price: ";

Page 122: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

122

1992-2007 Pearson Education, Inc. All rights reserved.

public CheckBoxFrame0() {

setLayout(new FlowLayout());// creating and adding textField priceLabel = new JLabel(priceString+totalPrice); add(priceLabel);

// creating and adding checkBox objects cheeseCheckBox = new JCheckBox("Cheese"); salamiCheckBox = new JCheckBox("Salami"); add(cheeseCheckBox); add(salamiCheckBox);

// registering events to the checkBoxes CheckBoxHandler handler = new CheckBoxHandler();

cheeseCheckBox.addItemListener(handler); salamiCheckBox.addItemListener(handler);

} // end constructor

Page 123: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

123

1992-2007 Pearson Education, Inc. All rights reserved.

class ChackBoxHandler

private class CheckBoxHandler implements ItemListener {

public void itemStateChanged(ItemEvent event) { if(event.getSource()==cheeseCheckBox) totalPrice += cheeseCheckBox.isSelected() ? priceCheese

:-priceCheese ; if(event.getSource()==salamiCheckBox)

totalPrice += salamiCheckBox.isSelected() ? priceSalami

:- priceSalami ; priceLabel.setText(priceString+totalPrice); } // end ItemSteteChanged method

} // end CheckBoxHandler inner class} // end CheckBoxFrame0 class

Page 124: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

124

1992-2007 Pearson Education, Inc. All rights reserved.

Another version of the CheckBoxHandler

private class CheckBoxHandler implements ItemListener {

public void itemStateChanged(ItemEvent event) { if(cheeseCheckBox.isSelected() &&

salamiCheckBox.isSelected()) totalPrice = priceCheese+priceSalami+pricePlain; else if(cheeseCheckBox.isSelected())

totalPrice = priceCheese+pricePlain; else if(salamiCheckBox.isSelected())

totalPrice = priceSalami+pricePlain; else

totalPrice = pricePlain; priceLabel.setText(priceString+totalPrice);

} // end ItemSteteChanged method } // end CheckBoxHandler inner class

} // end CheckBoxFrame0 class

Page 125: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

125

1992-2007 Pearson Education, Inc. All rights reserved.

Page 126: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

126

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxFrame.java

(1 of 3)

3 import java.awt.FlowLayout;

4 import java.awt.Font;

5 import java.awt.event.ItemListener;

6 import java.awt.event.ItemEvent;

7 import javax.swing.JFrame;

8 import javax.swing.JTextField;

9 import javax.swing.JCheckBox;

10

11 public class CheckBoxFrame extends JFrame

12 {

13 private JTextField textField; // displays text in changing fonts

14 private JCheckBox boldJCheckBox; // to select/deselect bold

15 private JCheckBox italicJCheckBox; // to select/deselect italic

16

17 // CheckBoxFrame constructor adds JCheckBoxes to JFrame

18 public CheckBoxFrame()

19 {

20 super( "JCheckBox Test" );

21 setLayout( new FlowLayout() ); // set frame layout

22

23 // set up JTextField and set its font

24 textField = new JTextField( "Watch the font style change", 20 );

25 textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) );

26 add( textField ); // add textField to JFrame

Page 127: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

127

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxFrame.java

(2 of 3)

28 boldJCheckBox = new JCheckBox( "Bold" ); // create bold checkbox

29 italicJCheckBox = new JCheckBox( "Italic" ); // create italic

30 add( boldJCheckBox ); // add bold checkbox to JFrame

31 add( italicJCheckBox ); // add italic checkbox to JFrame

32

33 // register listeners for JCheckBoxes

34 CheckBoxHandler handler = new CheckBoxHandler();

35 boldJCheckBox.addItemListener( handler );

36 italicJCheckBox.addItemListener( handler );

37 } // end CheckBoxFrame constructor

38

39 // private inner class for ItemListener event handling

40 private class CheckBoxHandler implements ItemListener

41 {

42 private int valBold = Font.PLAIN; // controls bold font style

43 private int valItalic = Font.PLAIN; // controls italic font style

44

45 // respond to checkbox events

46 public void itemStateChanged( ItemEvent event )

47 {

48 // process bold checkbox events

49 if ( event.getSource() == boldJCheckBox )

50 valBold =

51 boldJCheckBox.isSelected() ? Font.BOLD : Font.PLAIN;

52

Page 128: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

128

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxFrame.java

(3 of 3)

53 // process italic checkbox events

54 if ( event.getSource() == italicJCheckBox )

55 valItalic =

56 italicJCheckBox.isSelected() ? Font.ITALIC : Font.PLAIN;

57

58 // set text field font

59 textField.setFont(

60 new Font( "Serif", valBold + valItalic, 14 ) );

61 } // end method itemStateChanged

62 } // end private inner class CheckBoxHandler

63 } // end class CheckBoxFrame

Page 129: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

129

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxTest.java

1 // Fig. 11.18: CheckBoxTest.java

2 // Testing CheckBoxFrame.

3 import javax.swing.JFrame;

4

5 public class CheckBoxTest

6 {

7 public static void main( String args[] )

8 {

9 CheckBoxFrame checkBoxFrame = new CheckBoxFrame();

10 checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 checkBoxFrame.setSize( 275, 100 ); // set frame size

12 checkBoxFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class CheckBoxTest

Page 130: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

130

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxTest.java

Page 131: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

131

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

CheckBoxFrame.java

(2 of 3)

39 // private inner class for ItemListener event handling

40 private class CheckBoxHandler implements ItemListener

41 {

42 Font font = null; // controls bold font style

45 // respond to checkbox events

46 public void itemStateChanged( ItemEvent event )

47 {

48 // process bold checkbox events

49 if (boldJCheckBox.isSelected() && italicJCheckBox.isSelected())

50 font = new Font(“Sherif”,Font.BOLD : Font.PLAIN,14);

49 else if (boldJCheckBox.isSelected())

50 font = new Font(“Sherif”,Font.BOLD,14);

49 else if (italicJCheckBox.isSelected())

50 font = new Font(“Sherif”,Font.ITALIC,14); 49 else

50 font = new Font(“Sherif”,Font.PLAIN,14); textField.setFont(font);

61 } // end method itemStateChanged

62 } // end private inner class CheckBoxHandler

63 } // end class CheckBoxFrame

Page 132: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

132

1992-2007 Pearson Education, Inc. All rights reserved.

11.9.2 JRadioButton

•JRadioButton– Has two states – selected and unselected

– Normally appear in a group in which only one radio button can be selected at once

• Group maintained by a ButtonGroup object

– Declares method add to add a JRadioButton to group

– Usually represents mutually exclusive options

Page 133: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

133

1992-2007 Pearson Education, Inc. All rights reserved.

11.9.2 JRadioButton

• Event listener:– ItemListener– has the abstract method: itemStateChanged– Taking an event ItemEvent

• When on of the radio buttons is selected an – ItemEvent object is created that cantain information about

the event:• Source

– The ItemListener infterface’s itemStateChanged method process that event taking an ItemEvent object as parameter

Page 134: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

134

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.3

Adding a ButtonGroup object (or an object of any other class that does not derive from Component) to a container results in a compilation error.

Page 135: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

135

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class RadioButton0 {

public static void main(String[] args) {RadioButtonFrame0 radioButtonFrame0 = new

RadioButtonFrame0(“Radio Button Example");radioButtonFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

radioButtonFrame0.setSize(400, 200);radioButtonFrame0.setVisible(true);

}}

Page 136: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

136

1992-2007 Pearson Education, Inc. All rights reserved.

class RadioButton0 extends jFrame {

private JLabel label;

private JRadioButton maleRadioButton;

private JRadioButton femaleRadioButton;

private ButtonGroup genderGrup; new;

Page 137: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

137

1992-2007 Pearson Education, Inc. All rights reserved.

public RadioButtonFrame0(String title) {

super(title);setLayout(new FlowLayout());

label = new JLabel(“gender is female");add(label);

maleRadioButton = new JRadioButton(“Male",false); femaleRadioButton = new JRadioButton(“Female",true);

genderGrup = new ButtonGroup();genderGrup.add(maleRadioButton);genderGrup.add(femaleRadioButton);

Page 138: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

138

1992-2007 Pearson Education, Inc. All rights reserved.

add(mleRadioButton);add(femaleRadioButton);

RadioButtonHandler handler = new RadioButtonHandler();

maleRadioButton.addItemListener(handler);femaleRadioButton.addItemListener(handler);

} // end of constructor

Page 139: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

139

1992-2007 Pearson Education, Inc. All rights reserved.

private class RadioButtonHandler implements ItemListener {

public void itemStateChanged(ItemEvent event) { if(event.getSource() instanceof JRadioButton) {

if(boyRadioButton.isSelected()) label.setText(“gender is male"); if(girlRadioButton.isSelected()) label.setText(“gender is female");

}

} // end ItemSteteChanged method } // end Handler inner class

} // end RadioButtonFrame0 class

Page 140: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

140

1992-2007 Pearson Education, Inc. All rights reserved.

Page 141: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

141

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonFrame.java

(1 of 3)

3 import java.awt.FlowLayout;

4 import java.awt.Font;

5 import java.awt.event.ItemListener;

6 import java.awt.event.ItemEvent;

7 import javax.swing.JFrame;

8 import javax.swing.JTextField;

9 import javax.swing.JRadioButton;

10 import javax.swing.ButtonGroup;

11

12 public class RadioButtonFrame extends JFrame

13 {

14 private JTextField textField; // used to display font changes

15 private Font plainFont; // font for plain text

16 private Font boldFont; // font for bold text

17 private Font italicFont; // font for italic text

18 private Font boldItalicFont; // font for bold and italic text

19 private JRadioButton plainJRadioButton; // selects plain text

20 private JRadioButton boldJRadioButton; // selects bold text

21 private JRadioButton italicJRadioButton; // selects italic text

22 private JRadioButton boldItalicJRadioButton; // bold and italic

23 private ButtonGroup radioGroup; // buttongroup to hold radio buttons

Page 142: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

142

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonFrame.java

(1 of 3)

25 // RadioButtonFrame constructor adds JRadioButtons to JFrame

26 public RadioButtonFrame()

27 {

28 super( "RadioButton Test" );

29 setLayout( new FlowLayout() ); // set frame layout

30

31 textField = new JTextField( "Watch the font style change", 25 );

32 add( textField ); // add textField to JFrame

33

34 // create radio buttons

35 plainJRadioButton = new JRadioButton( "Plain", true );

36 boldJRadioButton = new JRadioButton( "Bold", false );

37 italicJRadioButton = new JRadioButton( "Italic", false );

38 boldItalicJRadioButton = new JRadioButton( "Bold/Italic", false );

39 add( plainJRadioButton ); // add plain button to JFrame

40 add( boldJRadioButton ); // add bold button to JFrame

41 add( italicJRadioButton ); // add italic button to JFrame

42 add( boldItalicJRadioButton ); // add bold and italic button

43

44 // create logical relationship between JRadioButtons

45 radioGroup = new ButtonGroup(); // create ButtonGroup

46 radioGroup.add( plainJRadioButton ); // add plain to group

47 radioGroup.add( boldJRadioButton ); // add bold to group

48 radioGroup.add( italicJRadioButton ); // add italic to group

49 radioGroup.add( boldItalicJRadioButton ); // add bold and italic

Page 143: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

143

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonFrame.java

(2 of 3)

51 // create font objects

52 plainFont = new Font( "Serif", Font.PLAIN, 14 );

53 boldFont = new Font( "Serif", Font.BOLD, 14 );

54 italicFont = new Font( "Serif", Font.ITALIC, 14 );

55 boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );

56 textField.setFont( plainFont ); // set initial font to plain

57

58 // register events for JRadioButtons

59 plainJRadioButton.addItemListener(

60 new RadioButtonHandler( plainFont ) );

61 boldJRadioButton.addItemListener(

62 new RadioButtonHandler( boldFont ) );

63 italicJRadioButton.addItemListener(

64 new RadioButtonHandler( italicFont ) );

65 boldItalicJRadioButton.addItemListener(

66 new RadioButtonHandler( boldItalicFont ) );

67 } // end RadioButtonFrame constructor

Page 144: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

144

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonFrame.java

(3 of 3)

69 // private inner class to handle radio button events

70 private class RadioButtonHandler implements ItemListener

71 {

72 private Font font; // font associated with this listener

73

74 public RadioButtonHandler( Font f )

75 {

76 font = f; // set the font of this listener

77 } // end constructor RadioButtonHandler

78

79 // handle radio button events

80 public void itemStateChanged( ItemEvent event )

81 {

82 textField.setFont( font ); // set font of textField

83 } // end method itemStateChanged

84 } // end private inner class RadioButtonHandler

85 } // end class RadioButtonFrame

Page 145: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

145

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonTest.java 1 // Fig. 11.20: RadioButtonTest.java

2 // Testing RadioButtonFrame.

3 import javax.swing.JFrame;

4

5 public class RadioButtonTest

6 {

7 public static void main( String args[] )

8 {

9 RadioButtonFrame radioButtonFrame = new RadioButtonFrame();

10 radioButtonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 radioButtonFrame.setSize( 300, 100 ); // set frame size

12 radioButtonFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class RadioButtonTest

Page 146: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

146

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonTest.java

Page 147: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

147

1992-2007 Pearson Education, Inc. All rights reserved.

Another version of the RadioButtonFrame class// Changing fornt of a text with radio buttons// modified version of books exampleimport javax.swing.*;import java.awt.*;import java.awt.event.*;

public class RadioButtonFrame extends JFrame {

private JTextField textField;private JRadioButton italicRadioButton;private JRadioButton boldRadioButton;private JRadioButton italicveboldRadioButton;private JRadioButton plainRadioButton;private ButtonGroup fontGrup;

Page 148: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

148

1992-2007 Pearson Education, Inc. All rights reserved.

public RadioButtonFrame() {

setLayout(new FlowLayout());

textField = new JTextField(“trail",20);textField.setFont(new Font("Serif",Font.PLAIN,14));add(textField);

boldRadioButton = new JRadioButton("Bold",false); italicRadioButton = new JRadioButton("Italic",false);italicveboldRadioButton = new

JRadioButton("italic&bold",false); plainRadioButton = new JRadioButton("plain",true);fontGrup = new ButtonGroup();

fontGrup.add(boldRadioButton);fontGrup.add(italicRadioButton);fontGrup.add(italicveboldRadioButton);fontGrup.add(plainRadioButton);

Page 149: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

149

1992-2007 Pearson Education, Inc. All rights reserved.

add(boldRadioButton);add(italicRadioButton);add(italicveboldRadioButton);add(plainRadioButton);

RadioButtonHandler handler = new RadioButtonHandler();

boldRadioButton.addItemListener(handler);

italicveboldRadioButton.addItemListener(handler);italicRadioButton.addItemListener(handler);plainRadioButton.addItemListener(handler);

} // end of constructor

Page 150: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

150

1992-2007 Pearson Education, Inc. All rights reserved.

private class RadioButtonHandler implements ItemListener {

private int valFont = Font.PLAIN;private Font newFont;

public void itemStateChanged(ItemEvent event){

if(event.getSource() instanceof JRadioButton) { if(boldRadioButton.isSelected())

valFont = Font.BOLD ; if(italicRadioButton.isSelected())

valFont = Font.ITALIC; if(italicveboldRadioButton.isSelected())

valFont = Font.ITALIC+Font.BOLD; if(plainRadioButton.isSelected())

valFont = Font.PLAIN;}

Page 151: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

151

1992-2007 Pearson Education, Inc. All rights reserved.

newFont = new Font("Serif",valFont,14);

textField.setFont(newFont);

} // end method ItemSteteChanged

} // end inner class RadioButtonHandler

} // end class RadioButtonFrame

Page 152: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

152

1992-2007 Pearson Education, Inc. All rights reserved.

11.10 JComboBox and Using an Anonymous Inner Class for Event Handling

• Combo box– Also called a drop-down list

• list of items from which user makes a single selection

– Implemented by class JComboBox

– generates ItemEvents or ActionEvents • JCheckBox and JRadioButton

– Each item in the list has an index

– when an item is seleced generates ActionEvent

Page 153: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

153

1992-2007 Pearson Education, Inc. All rights reserved.

some JComboBox methods

•setMaximumRowCount sets the maximum number of rows shown at once

•JComboBox provides a scrollbar and up and down arrows to traverse list

• Which item of in the displayed list is selected ?– How to get this information about the selected item?

•getSelectedIndex method of JComboBox class returns the selected index

Page 154: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

154

1992-2007 Pearson Education, Inc. All rights reserved.

Constructors of JComboBox

• JComboBox()– creates a default empty combobox

• JComboBox(Object[] o)– creates a combobox that contains the elements in the

specified array

• Example:– String letterGradess[] =

{“AA”,”BA”,”BB”,”CB”,”CC”,”F”};

– JComboBox letterCombo = new JComboBox(letterGrades);

Page 155: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

155

1992-2007 Pearson Education, Inc. All rights reserved.

getting what is selected

• int getSelectedIndex()– returns the index of the item selected

• Object getSelectedI tem()– returns the selected item

Page 156: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

156

1992-2007 Pearson Education, Inc. All rights reserved.

Example of ComboBox

• Select an employee from a combobox and list her name, lastname and wage to a textArea

• The ComboBoxFrame class that extends from JFrame:– names,last names and wages of 5 employees

– a combobox and a textArea

– Select an employee from the combo and her name, lastname and wage are displayed in the textArea

• Here – the ActionEvent is generated when an item is selected

– ActionListener is implemented

– actionPerformed method is invoked

Page 157: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

157

1992-2007 Pearson Education, Inc. All rights reserved.

The test class

import javax.swing.*;

import java.awt.*;import java.awt.event.*;public class ComboBox0 {public static void main(String[] args) { ComboBoxFrame comboBoxFrame = new ComboBoxFrame();

comboBoxFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); comboBoxFrame.setSize(400, 200); comboBoxFrame.setVisible(true);}

}

Page 158: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

158

1992-2007 Pearson Education, Inc. All rights reserved.

ComboBoxFrame class

class ComboBoxFrame extends JFrame {

private JComboBox combo;private JTextArea status;

String names[] = {"Ali","Burak","Can","Derya","Elif"};String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"};int wages[] = {1000,1500,1200,800,900};

public ComboBoxFrame() {setLayout(new FlowLayout(FlowLayout.LEFT,10,30));combo = new JComboBox(names);status = new JTextArea(7,25);

add(combo);add(status);

ComboBoxHandler handler = new ComboBoxHandler();combo.addActionListener(handler);

} // end constructor

Page 159: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

159

1992-2007 Pearson Education, Inc. All rights reserved.

ComboBoxHandler inner class

private class ComboBoxHandler implements ActionListener {

public void actionPerformed(ActionEvent e){

int i = combo.getSelectedIndex();status.setText("");status.append("Name:"+names[i]+"\n");status.append("LastName:"+lastNames[i]+"\n");status.append("Wage:"+wages[i]);

} // end method } // end inner class ComboBoxHandler

} // end class ComboBoxFrame

Page 160: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

160

1992-2007 Pearson Education, Inc. All rights reserved.

output of the program

Page 161: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

161

1992-2007 Pearson Education, Inc. All rights reserved.

Anonymous Inner Class for Event Handling

• Anonymous inner class– Special form of inner class

– Declared without a name

– Typically appears inside a method call

– Has limited access to local variables

Page 162: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

162

1992-2007 Pearson Education, Inc. All rights reserved.

Anonymous Inner Class for Event Handling

– extends a superclass or implements an interface

– uses either• no arg –default constructor of its superclass or

• if imlements an interface uses Objcect()

– declared like that:• new SuperClass name or Interface name () {

imlements abstract method s of superclass

or all methods of the interface

or can have its own methods

}

Page 163: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

163

1992-2007 Pearson Education, Inc. All rights reserved.

ComboBoxFrame class with an anonymous class

// with anonumous class implementatitionclass ComboBoxFrame extends JFrame {

private JComboBox combo;private JTextArea status;

String names[] = {"Ali","Burak","Can","Derya","Elif"};String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"};int wages[] = {1000,1500,1200,800,900};

public ComboBoxFrame() {setLayout(new FlowLayout(FlowLayout.LEFT,10,30));combo = new JComboBox(names);status = new JTextArea(7,25);

add(combo);add(status);

Page 164: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

164

1992-2007 Pearson Education, Inc. All rights reserved.

the anonymous class

combo.addActionListener( // invoke method new ActionListener() { // anonymous class begins public void actionPerformed(ActionEvent e) {

int i = combo.getSelectedIndex(); status.setText(""); status.append("Name:"+names[i]+"\

n");

status.append("LastName:"+lastNames[i]+"\n"); status.append("Wage:"+wages[i]);

} // end method} // end anonymous class ComboBoxHandler); // end invoking addActionListener method

} // end constructor} // end class ComboBoxFrame

Page 165: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

165

1992-2007 Pearson Education, Inc. All rights reserved.

11.10 JComboBox and Using an Anonymous Inner Class for Event Handling

• following example– list of four image file names

– user selects one and the corresponding icın is displayed as a label

• Names of the images are held in a String array– lines 17-18

• Images files are stored in the same directory are obtained and stored in array of ImageIcons

– lines 19-23

• JComboBox constructor accepts an array parameter – the names of images to be listed – a selction is to be made

Page 166: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

166

1992-2007 Pearson Education, Inc. All rights reserved.

11.10 JComboBox and Using an Anonymous Inner Class for Event Handling

– setMaximumRowCount sets the maximum number of rows shown at once

– JComboBox provides a scrollbar and up and down arrows to traverse list

• at line 49:– label = new JLabel(icons[0]);

• lablel is instantiated with a constructor accepting an Icon object as teh parameter – no text is set

Page 167: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

167

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.11

Set the maximum row count for a JComboBox to a number of rows that prevents the list from expanding outside the bounds of the window in which it is used. This configuration will ensure that the list displays correctly when it is expanded by the user.

Page 168: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

168

1992-2007 Pearson Education, Inc. All rights reserved.

Using an Anonymous Inner Class for Event Handling

• Anonymous inner class– Special form of inner class

– Declared without a name

– Typically appears inside a method call

– Has limited access to local variables

Page 169: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

169

1992-2007 Pearson Education, Inc. All rights reserved.

Using an Anonymous Inner Class for Event Handling

• Anonymous inner class– Special form of inner class

– Declared without a name

– Typically appears inside a method call

– Has limited access to local variables

Page 170: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

170

1992-2007 Pearson Education, Inc. All rights reserved.

Using an Anonymous Inner Class for Event Handling

– extends a superclass or implements an interface

– uses either• no arg –default constructor of its superclass or

• if imlements an interface uses Objcect()

– declared like that:• new SuperClass name or Interface name () {

imlements abstract method s of superclass or all methods of

the interface

or can have its own methods

}

Page 171: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

171

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxFrame.java

(1 of 2)

3 import java.awt.FlowLayout;

4 import java.awt.event.ItemListener;

5 import java.awt.event.ItemEvent;

6 import javax.swing.JFrame;

7 import javax.swing.JLabel;

8 import javax.swing.JComboBox;

9 import javax.swing.Icon;

10 import javax.swing.ImageIcon;

11

12 public class ComboBoxFrame extends JFrame

13 {

14 private JComboBox imagesJComboBox; // combobox to hold names of icons

15 private JLabel label; // label to display selected icon

16

17 private String names[] =

18 { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };

19 private Icon icons[] = {

20 new ImageIcon( getClass().getResource( names[ 0 ] ) ),

21 new ImageIcon( getClass().getResource( names[ 1 ] ) ),

22 new ImageIcon( getClass().getResource( names[ 2 ] ) ),

23 new ImageIcon( getClass().getResource( names[ 3 ] ) ) };

Page 172: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

172

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxFrame.java

(1 of 2)

25 // ComboBoxFrame constructor adds JComboBox to JFrame

26 public ComboBoxFrame()

27 {

28 super( "Testing JComboBox" );

29 setLayout( new FlowLayout() ); // set frame layout

30 31 imagesJComboBox = new JComboBox( names ); // set up JComboBox 32 imagesJComboBox.setMaximumRowCount( 3 ); // display three rows 33

34 imagesJComboBox.addItemListener(

35 new ItemListener() // anonymous inner class

36 {

37 // handle JComboBox event 38 public void itemStateChanged( ItemEvent event ) 39 {

40 // determine whether check box selected 41 if ( event.getStateChange() == ItemEvent.SELECTED ) 42 label.setIcon( icons[ 43 imagesJComboBox.getSelectedIndex() ] ); 44 } // end method itemStateChanged

45 } // end anonymous inner class

46 ); // end call to addItemListener

Page 173: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

173

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxFrame.java

(1 of 2)25 // ComboBoxFrame constructor adds JComboBox to JFrame

26 public ComboBoxFrame()

27 {

28 super( "Testing JComboBox" );

29 setLayout( new FlowLayout() ); // set frame layout

30 31 imagesJComboBox = new JComboBox( names ); // set up JComboBox 32 imagesJComboBox.setMaximumRowCount( 3 ); // display three rows 33

Page 174: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

174

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxFrame.java

(1 of 2)

34 imagesJComboBox.addItemListener(

35 new ItemListener() // anonymous inner class

36 {

37 // handle JComboBox event 38 public void itemStateChanged( ItemEvent event ) 39 {

40 // determine whether check box selected 41 if ( event.getStateChange() == ItemEvent.SELECTED ) 42 label.setIcon( icons[ 43 imagesJComboBox.getSelectedIndex() ] ); 44 } // end method itemStateChanged

45 } // end anonymous inner class

46 ); // end call to addItemListener

Page 175: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

175

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxFrame.java

(1 of 2)

48 add( imagesJComboBox ); // add combobox to JFrame

49 label = new JLabel( icons[ 0 ] ); // display first icon

50 add( label ); // add label to JFrame

51 } // end ComboBoxFrame constructor

52 } // end class ComboBoxFrame

Page 176: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

176

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ComboBoxTest.java

1 // Fig. 11.22: ComboBoxTest.java

2 // Testing ComboBoxFrame.

3 import javax.swing.JFrame;

4

5 public class ComboBoxTest

6 {

7 public static void main( String args[] )

8 {

9 ComboBoxFrame comboBoxFrame = new ComboBoxFrame();

10 comboBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 comboBoxFrame.setSize( 350, 150 ); // set frame size 12 comboBoxFrame.setVisible( true ); // display frame 13 } // end main

14 } // end class ComboBoxTest

Page 177: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

177

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Scrollbar to scroll through the items in the list

scroll arrows scroll box

Page 178: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

178

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.5

An anonymous inner class declared in a method can access the instance variables and methods of the top-level class object that declared it, as well as the method’s final local variables, but cannot access the method’s non-final variables.

Page 179: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

179

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.6

Like any other class, when an anonymous inner class implements an interface, the class must implement every method in the interface.

Page 180: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

180

1992-2007 Pearson Education, Inc. All rights reserved.

imagesJComboBox.addItemListener(

new ItemListener() // anonymous inner class {

// handle JComboBox event

public void itemStateChanged( ItemEvent event )

{

// determine whether check box selected

if ( event.getStateChange() == ItemEvent.SELECTED )

label.setIcon( icons[

imagesJComboBox.getSelectedIndex() ] );

} // end method itemStateChanged } // end anonymous inner class

); // end call to addItemListener

Page 181: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

181

1992-2007 Pearson Education, Inc. All rights reserved.

imagesJComboBox.addItemListener( new ItemListener() { /* body of anonymous inner class no class name ItemListener is the interface the anonymous inner class implements create an object no reference is defined even the class of the object has no name but imlements an interface */ } // end anonymous inner class ); // end call to addItemListener

Page 182: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

182

1992-2007 Pearson Education, Inc. All rights reserved.

imagesJComboBox.addItemListener( new ItemListener() { // handle JComboBox event

public void itemStateChanged( ItemEvent event )

{ // indisde the method } // end method itemStateChanged } // end anonymous inner class ); // end call to addItemListener

Page 183: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

183

1992-2007 Pearson Education, Inc. All rights reserved.

public void itemStateChanged( ItemEvent event ){ // determine whether check box selected if ( event.getStateChange() == ItemEvent.SELECTED )

label.setIcon( icons[

imagesJComboBox.getSelectedIndex() ] ); } // end method itemStateChanged the check box is seleced if

event’s getStateChange() nethod returns a constant which is equal to the ItemEvent.SELECED constant

what to do then !

Page 184: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

184

1992-2007 Pearson Education, Inc. All rights reserved.

if ( event.getStateChange() == ItemEvent.SELECTED )

label.setIcon( icons[ imagesJComboBox.getSelectedIndex() ] );

the getSelectedIndex() method of the JCheckBox class

returns the index of the item seleced

label.setIcon(Icon ic) method sets the icon of label

its argument is the Icon object to be added to the label

here the Icon object is one of the members of the icons array whose index is seleced

longer version is given in next slide

Page 185: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

185

1992-2007 Pearson Education, Inc. All rights reserved.

inside the if statement could be written in another wet – avşt longer

if ( event.getStateChange() == ItemEvent.SELECTED )

{

int i = imagesJComboBox.getSelectedIndex();

label.setIcon( icons[ i] );

}

the getSelectedIndex() method of the JCheckBox class

returns the index of the item seleced - here int i

label.setIcon(Icon ic) method sets the icon of label

its argument is the Icon object to be added to the label

here the Icon object is one of the members of the icons array whose index is seleced - icons[i]

Page 186: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

186

1992-2007 Pearson Education, Inc. All rights reserved.

11.11 JList

• List– Displays a series of items from which the user may select

one or more items

– Implemented by class JList

– Allows for single-selection lists or multiple-selection lists

– A ListSelectionEvent occurs when an item is selected• Handled by a ListSelectionListener and passed to

method valueChanged

Page 187: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

187

1992-2007 Pearson Education, Inc. All rights reserved.

11.11 JList

•In this example a list of 13 colors are created

– when a color is selected a ListSelectionEvent occurs

– the color of the background changes to the color seleced

•list of names of colors is argument to the constructor of JList object colorList

Page 188: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

188

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ListFrame.java

(1 of 2)

1 // Fig. 11.23: ListFrame.java

2 // Selecting colors from a JList.

3 import java.awt.FlowLayout;

4 import java.awt.Color;

5 import javax.swing.JFrame;

6 import javax.swing.JList;

7 import javax.swing.JScrollPane;

8 import javax.swing.event.ListSelectionListener;

9 import javax.swing.event.ListSelectionEvent;

10 import javax.swing.ListSelectionModel;

11

12 public class ListFrame extends JFrame

13 {

14 private JList colorJList; // list to display colors

15 private final String colorNames[] = { "Black", "Blue", "Cyan",

16 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",

17 "Orange", "Pink", "Red", "White", "Yellow" };

18 private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN,

19 Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY,

20 Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE,

21 Color.YELLOW };

Page 189: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

189

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ListFrame.java

(1 of 2)

24 public ListFrame()

25 {

26 super( "List Test" );

27 setLayout( new FlowLayout() ); // set frame layout

29 colorJList = new JList( colorNames ); // create with colorNames

30 colorJList.setVisibleRowCount( 5 ); // display five rows at once

31

32 // do not allow multiple selections

33 colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

34

35 // add a JScrollPane containing JList to frame

36 add( new JScrollPane( colorJList ) );

Page 190: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

190

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ListFrame.java

(2 of 2)

37

38 colorJList.addListSelectionListener(

39 new ListSelectionListener() // anonymous inner class

40 {

41 // handle list selection events

42 public void valueChanged( ListSelectionEvent event )

43 {

44 getContentPane().setBackground(

45 colors[ colorJList.getSelectedIndex() ] );

46 } // end method valueChanged

47 } // end anonymous inner class

48 ); // end call to addListSelectionListener

49 } // end ListFrame constructor

50 } // end class ListFrame

Page 191: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

191

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ListTest.java

1 // Fig. 11.24: ListTest.java

2 // Selecting colors from a JList.

3 import javax.swing.JFrame;

4

5 public class ListTest

6 {

7 public static void main( String args[] )

8 {

9 ListFrame listFrame = new ListFrame(); // create ListFrame

10 listFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 listFrame.setSize( 350, 150 ); // set frame size

12 listFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class ListTest

Page 192: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

192

1992-2007 Pearson Education, Inc. All rights reserved.

colorJList.addListSelectionListener(new ListSelectionListener() { public void valueChanged( ListSelectionEvent event ) { getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged } // end anonymous inner class ); // end call to addListSelectionListener} // end ListFrame constructor

} // end class ListFrame

Page 193: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

193

1992-2007 Pearson Education, Inc. All rights reserved.

colorJList.addListSelectionListener(new ListSelectionListener() { // body of anonymous inner class

//has the valueChanged method

} // end anonymous inner class); // end call to addListSelectionListenerthis inner class imlements ListSelectionListener

Page 194: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

194

1992-2007 Pearson Education, Inc. All rights reserved.

colorJList.addListSelectionListener(new ListSelectionListener() { public void valueChanged( ListSelectionEvent event ) {

// ListSelectionEvent is processed in that method } // end method valueChanged} // end anonymous inner class

); // end call to addListSelectionListenerthis inner class imlements ListSelectionListenerits value changed method is to be imlementedthe event type is ListSelection

Page 195: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

195

1992-2007 Pearson Education, Inc. All rights reserved.

public void valueChanged( ListSelectionEvent even){ getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged

what the valueChaned method does?

getSelectedIndex() method of a JList class returns the index

selected

setBackground method set

Page 196: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

196

1992-2007 Pearson Education, Inc. All rights reserved.

public void valueChanged( ListSelectionEvent even){

int i = colorJList.getSelectedIndex(); getContentPane().setBackground(colors[i]);} // end method valueChanged

A two step version of the same method

setBackground method sets the color of background the color is one of the members of the color array

method getContentPane

returns a reference to the JFrames content Pane

then its setBackground method is called

Page 197: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

197

1992-2007 Pearson Education, Inc. All rights reserved.

11.12 Multiple-Selection Lists

• Multiple-selection list– Enables users to select many items

– Single interval selection allows only a continuous range of items

– Multiple interval selection allows any set of elements to be selected

Page 198: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

198

1992-2007 Pearson Education, Inc. All rights reserved.

Simple Example

• Select products from a list

• display in a textArea:– products selected, their prices

– total payment

Page 199: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

199

1992-2007 Pearson Education, Inc. All rights reserved.

Test class List0

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.swing.event.*;public class List0 {

public static void main(String[] args){

ListFrame0 listFrame = new ListFrame0();

listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

listFrame.setSize(400, 200);listFrame.setVisible(true);

}}

Page 200: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

200

1992-2007 Pearson Education, Inc. All rights reserved.

class ListFrame0

class ListFrame0 extends JFrame {

private JList list;private JButton button;private JTextArea purchased;private String products[] = {"book","tea","cheese","bread","milk"};private int prices[] = {10,12,20,15,2};private int total;public ListFrame0() {

setLayout(new FlowLayout());

list = new JList(products);list.setVisibleRowCount(3);list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);button = new JButton("add");purchased = new JTextArea(7,25);

Page 201: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

201

1992-2007 Pearson Education, Inc. All rights reserved.

class ListFrame0 (cont.)

add(list);add(new JScrollPane(list));add(button);add(purchased); button.addActionListener(new

ListHandler());

} // end constructor

Page 202: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

202

1992-2007 Pearson Education, Inc. All rights reserved.

inner class ListHandler

private class ListHandler implements ActionListener {

public void actionPerformed(ActionEvent e){

if(e.getSource()==button){ total = 0; purchased.setText("purchased:"); int choice[] = list.getSelectedIndices(); for(int i = 0;i < choice.length;i++) { purchased.append("\n\t"+products[choice[i]]); purchased.append("\t"+prices[choice[i]]); total += prices[choice[i]]; } // end for purchased.append("\ntotal:\t"+total);} // end if

} // end method actionPerformed } // end inner class ListHandler

} // end class ListFrame0

Page 203: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

203

1992-2007 Pearson Education, Inc. All rights reserved.

output of the program

Page 204: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

204

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MultipleSelectionFrame.java

(1 of 3)

1 // Fig. 11.25: MultipleSelectionFrame.java

2 // Copying items from one List to another.

3 import java.awt.FlowLayout;

4 import java.awt.event.ActionListener;

5 import java.awt.event.ActionEvent;

6 import javax.swing.JFrame;

7 import javax.swing.JList;

8 import javax.swing.JButton;

9 import javax.swing.JScrollPane;

10 import javax.swing.ListSelectionModel;

11

12 public class MultipleSelectionFrame extends JFrame

13 {

14 private JList colorJList; // list to hold color names

15 private JList copyJList; // list to copy color names into

16 private JButton copyJButton; // button to copy selected names

17 private final String colorNames[] = { "Black", "Blue", "Cyan",

18 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange",

19 "Pink", "Red", "White", "Yellow" };

20

21 // MultipleSelectionFrame constructor

22 public MultipleSelectionFrame()

23 {

24 super( "Multiple Selection Lists" );

25 setLayout( new FlowLayout() ); // set frame layout

26

Page 205: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

205

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MultipleSelectionFrame.java

(2 of 3)

27 colorJList = new JList( colorNames ); // holds names of all colors

28 colorJList.setVisibleRowCount( 5 ); // show five rows

29 colorJList.setSelectionMode(

30 ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );

31 add( new JScrollPane( colorJList ) ); // add list with scrollpane

32

33 copyJButton = new JButton( "Copy >>>" ); // create copy button

34 copyJButton.addActionListener(

35

36 new ActionListener() // anonymous inner class

37 {

38 // handle button event

39 public void actionPerformed( ActionEvent event )

40 {

41 // place selected values in copyJList

42 copyJList.setListData( colorJList.getSelectedValues() );

43 } // end method actionPerformed

44 } // end anonymous inner class

45 ); // end call to addActionListener

46

Page 206: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

206

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MultipleSelectionFrame.java

(3 of 3)47 add( copyJButton ); // add copy button to JFrame

48

49 copyJList = new JList(); // create list to hold copied color names

50 copyJList.setVisibleRowCount( 5 ); // show 5 rows

51 copyJList.setFixedCellWidth( 100 ); // set width

52 copyJList.setFixedCellHeight( 15 ); // set height

53 copyJList.setSelectionMode(

54 ListSelectionModel.SINGLE_INTERVAL_SELECTION );

55 add( new JScrollPane( copyJList ) ); // add list with scrollpane

56 } // end MultipleSelectionFrame constructor

57 } // end class MultipleSelectionFrame

Page 207: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

207

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MultipleSelectionTest.java

1 // Fig. 11.26: MultipleSelectionTest.java

2 // Testing MultipleSelectionFrame.

3 import javax.swing.JFrame;

4

5 public class MultipleSelectionTest

6 {

7 public static void main( String args[] )

8 {

9 MultipleSelectionFrame multipleSelectionFrame =

10 new MultipleSelectionFrame();

11 multipleSelectionFrame.setDefaultCloseOperation(

12 JFrame.EXIT_ON_CLOSE );

13 multipleSelectionFrame.setSize( 350, 140 ); // set frame size

14 multipleSelectionFrame.setVisible( true ); // display frame

15 } // end main

16 } // end class MultipleSelectionTest

Page 208: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

208

1992-2007 Pearson Education, Inc. All rights reserved.

copyJButton = new JButton( "Copy >>>" ); // create copy button

copyJButton.addActionListener(

new ActionListener() // anonymous inner class { // handle button event public void actionPerformed( ActionEvent event ) { // place selected values in copyJList copyJList.setListData(

colorJList.getSelectedValues() ); } // end method actionPerformed } // end anonymous inner class); // end call to addActionListener

Page 209: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

209

1992-2007 Pearson Education, Inc. All rights reserved.

public void actionPerformed( ActionEvent event ) { // place selected values in copyJList copyJList.setListData(

colorJList.getSelectedValues() ); } // end method actionPerformedcolorJList.getSelectedValues()getSelectedValues() method called over colorList object returns array of objects selected by the user

setListData method called on copyList get this array as an argument seting its list elements

Page 210: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

210

1992-2007 Pearson Education, Inc. All rights reserved.

11.13 Mouse Event Handling

• Mouse events– Create a MouseEvent object

– Handled by MouseListeners and MouseMotionListeners

– MouseInputListener combines the two interfaces

Page 211: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

211

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.27 | MouseListener and MouseMotionListener interface methods. (Part 1 of 2.)

MouseListener and MouseMotionListener interface methods

Methods of interface MouseListener

public void mousePressed( MouseEvent event )

Called when a mouse button is pressed while the mouse cursor is on a component.

public void mouseClicked( MouseEvent event )

Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousePressed.

public void mouseReleased( MouseEvent event )

Called when a mouse button is released after being pressed. This event is always preceded by a call to mousePressed and one or more calls to mouseDragged.

public void mouseEntered( MouseEvent event )

Called when the mouse cursor enters the bounds of a component.

Page 212: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

212

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.27 | MouseListener and MouseMotionListener interface methods. (Part 2 of 2.)

MouseListener and MouseMotionListener interface methods

public void mouseExited( MouseEvent event )

Called when the mouse cursor leaves the bounds of a component.

Methods of interface MouseMotionListener

public void mouseDragged( MouseEvent event )

Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousePressed. All drag events are sent to the component on which the user began to drag the mouse.

public void mouseMoved( MouseEvent event )

Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned.

Page 213: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

213

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.12

Method calls to mouseDragged and mouseReleased are sent to the MouseMotionListener for the Component on which a mouse drag operation started. Similarly, the mouseReleased method call at the end of a drag operation is sent to the MouseListener for the Component on which the drag operation started.

Page 214: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

214

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(1 of 4)

1 // Fig. 11.28: MouseTrackerFrame.java

2 // Demonstrating mouse events.

3 import java.awt.Color;

4 import java.awt.BorderLayout;

5 import java.awt.event.MouseListener;

6 import java.awt.event.MouseMotionListener;

7 import java.awt.event.MouseEvent;

8 import javax.swing.JFrame;

9 import javax.swing.JLabel;

10 import javax.swing.JPanel;

11

12 public class MouseTrackerFrame extends JFrame

13 {

14 private JPanel mousePanel; // panel in which mouse events will occur

15 private JLabel statusBar; // label that displays event information

16

17 // MouseTrackerFrame constructor sets up GUI and

18 // registers mouse event handlers

19 public MouseTrackerFrame()

20 {

21 super( "Demonstrating Mouse Events" );

22

23 mousePanel = new JPanel(); // create panel

24 mousePanel.setBackground( Color.WHITE ); // set background color

25 add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame

26

27 statusBar = new JLabel( "Mouse outside JPanel" );

28 add( statusBar, BorderLayout.SOUTH ); // add label to JFrame

29

Page 215: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

215

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(2 of 4)30 // create and register listener for mouse and mouse motion events

31 MouseHandler handler = new MouseHandler();

32 mousePanel.addMouseListener( handler );

33 mousePanel.addMouseMotionListener( handler );

34 } // end MouseTrackerFrame constructor

35

36 private class MouseHandler implements MouseListener,

37 MouseMotionListener

38 {

39 // MouseListener event handlers

40 // handle event when mouse released immediately after press

41 public void mouseClicked( MouseEvent event )

42 {

43 statusBar.setText( String.format( "Clicked at [%d, %d]",

44 event.getX(), event.getY() ) );

45 } // end method mouseClicked

46

Page 216: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

216

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(2 of 4)47 // handle event when mouse pressed

48 public void mousePressed( MouseEvent event )

49 {

50 statusBar.setText( String.format( "Pressed at [%d, %d]",

51 event.getX(), event.getY() ) );

52 } // end method mousePressed

53

54 // handle event when mouse released after dragging

55 public void mouseReleased( MouseEvent event )

56 {

57 statusBar.setText( String.format( "Released at [%d, %d]",

58 event.getX(), event.getY() ) );

59 } // end method mouseReleased

Page 217: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

217

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(3 of 4)

60

61 // handle event when mouse enters area

62 public void mouseEntered( MouseEvent event )

63 {

64 statusBar.setText( String.format( "Mouse entered at [%d, %d]",

65 event.getX(), event.getY() ) );

66 mousePanel.setBackground( Color.GREEN );

67 } // end method mouseEntered

68

69 // handle event when mouse exits area

70 public void mouseExited( MouseEvent event )

71 {

72 statusBar.setText( "Mouse outside JPanel" );

73 mousePanel.setBackground( Color.WHITE );

74 } // end method mouseExited

75

Page 218: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

218

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(4 of 4)

76 // MouseMotionListener event handlers

77 // handle event when user drags mouse with button pressed

78 public void mouseDragged( MouseEvent event )

79 {

80 statusBar.setText( String.format( "Dragged at [%d, %d]",

81 event.getX(), event.getY() ) );

82 } // end method mouseDragged

83

84 // handle event when user moves mouse

85 public void mouseMoved( MouseEvent event )

86 {

87 statusBar.setText( String.format( "Moved at [%d, %d]",

88 event.getX(), event.getY() ) );

89 } // end method mouseMoved

90 } // end inner class MouseHandler

91 } // end class MouseTrackerFrame

Page 219: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

219

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(1 of 2)

1 // Fig. 11.29: MouseTrackerFrame.java

2 // Testing MouseTrackerFrame.

3 import javax.swing.JFrame;

4

5 public class MouseTracker

6 {

7 public static void main( String args[] )

8 {

9 MouseTrackerFrame mouseTrackerFrame = new MouseTrackerFrame();

10 mouseTrackerFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 mouseTrackerFrame.setSize( 300, 100 ); // set frame size

12 mouseTrackerFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class MouseTracker

Page 220: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

220

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseTrackerFrame.java

(2 of 2)

Page 221: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

221

1992-2007 Pearson Education, Inc. All rights reserved.

// Fig. 11.28: MouseTrackerFrame.java// Demonstrating mouse events.import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.MouseEvent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;

public class MouseTrackerFrame extends JFrame { private JPanel mousePanel; // panel in which mouse events will occur

private JLabel statusBar; // label that displays event information

Page 222: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

222

1992-2007 Pearson Education, Inc. All rights reserved.

// MouseTrackerFrame constructor sets up GUI and // registers mouse event handlers public MouseTrackerFrame() { super( "Demonstrating Mouse Events" );

mousePanel = new JPanel(); // create panel mousePanel.setBackground( Color.WHITE ); // set background color add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame

statusBar = new JLabel( "Mouse outside JPanel" ); add( statusBar, BorderLayout.SOUTH ); // add label to JFrame

// create and register listener for mouse and mouse motion events MouseHandler handler = new MouseHandler();

mousePanel.addMouseListener( handler ); mousePanel.addMouseMotionListener( handler );

} // end MouseTrackerFrame constructor

Page 223: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

223

1992-2007 Pearson Education, Inc. All rights reserved.

// private class MouseHandler implements MouseListener, MouseMotionListener {

// MouseListener event handlers // handle event when mouse released immediately after press public void mouseClicked( MouseEvent event ) {

statusBar.setText( String.format( "Clicked at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseClicked

// handle event when mouse pressed public void mousePressed( MouseEvent event ) {

statusBar.setText( String.format( "Pressed at [%d, %d]", event.getX(), event.getY() ) ); } // end method mousePressed

Page 224: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

224

1992-2007 Pearson Education, Inc. All rights reserved.

// handle event when mouse released after dragging public void mouseReleased( MouseEvent event ) {

statusBar.setText( String.format( "Released at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseReleased

// handle event when mouse enters area public void mouseEntered( MouseEvent event ) { statusBar.setText( String.format( "Mouse entered at [%d, %d]",

event.getX(), event.getY() ) ); mousePanel.setBackground( Color.GREEN );

} // end method mouseEntered

// handle event when mouse exits area public void mouseExited( MouseEvent event ) {

statusBar.setText( "Mouse outside JPanel" ); mousePanel.setBackground( Color.WHITE );

} // end method mouseExited

Page 225: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

225

1992-2007 Pearson Education, Inc. All rights reserved.

// MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mouseDragged( MouseEvent event ) { statusBar.setText( String.format( "Dragged at [%d, %d]", event.getX(), event.getY() ) );

} // end method mouseDragged

// handle event when user moves mouse public void mouseMoved( MouseEvent event ) { statusBar.setText( String.format( "Moved at [%d, %d]", event.getX(), event.getY() ) );

} // end method mouseMoved } // end inner class MouseHandler} // end class MouseTrackerFrample

Page 226: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

226

1992-2007 Pearson Education, Inc. All rights reserved.

11.14 Adapter Classes

• Adapter class– Implements event listener interface

– Provides default implementation for all event-handling methods

Page 227: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

227

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 11.7

When a class implements an interface, the class has an “is a” relationship with that interface. All direct and indirect subclasses of that class inherit this interface. Thus, an object of a class that extends an event-adapter class is an object of the corresponding event-listener type (e.g., an object of a subclass of MouseAdapter is a MouseListener).

Page 228: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

228

1992-2007 Pearson Education, Inc. All rights reserved.

Extending MouseAdapter

•MouseAdapter– Adapter class for MouseListener and MouseMotionListener interfaces

– Extending class allows you to override only the methods you wish to use

Page 229: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

229

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.4

If you extend an adapter class and misspell the name of the method you are overriding, your method simply becomes another method in the class. This is a logic error that is difficult to detect, since the program will call the empty version of the method inherited from the adapter class.

Page 230: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

230

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.30 | Event-adapter classes and the interfaces they implement in package java.awt.event.

Event-adapter class in java.awt.event Implements interface

ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener

Page 231: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

231

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseDetailsFrame.java

(1 of 2)

3 import java.awt.BorderLayout;

4 import java.awt.Graphics;

5 import java.awt.event.MouseAdapter;

6 import java.awt.event.MouseEvent;

7 import javax.swing.JFrame;

8 import javax.swing.JLabel;

9

10 public class MouseDetailsFrame extends JFrame

11 {

12 private String details; // String representing

13 private JLabel statusBar; // JLabel that appears at bottom of window

14

15 // constructor sets title bar String and register mouse listener

16 public MouseDetailsFrame()

17 {

18 super( "Mouse clicks and buttons" );

19

20 statusBar = new JLabel( "Click the mouse" );

21 add( statusBar, BorderLayout.SOUTH );

22 addMouseListener( new MouseClickHandler() ); // add handler

23 } // end MouseDetailsFrame constructor

24

Page 232: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

232

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseDetailsFrame.java

(2 of 2)

25 // inner class to handle mouse events

26 private class MouseClickHandler extends MouseAdapter

27 {

28 // handle mouse click event and determine which button was pressed

29 public void mouseClicked( MouseEvent event )

30 {

31 int xPos = event.getX(); // get x position of mouse

32 int yPos = event.getY(); // get y position of mouse

33

34 details = String.format( "Clicked %d time(s)",

35 event.getClickCount() );

36

37 if ( event.isMetaDown() ) // right mouse button

38 details += " with right mouse button";

39 else if ( event.isAltDown() ) // middle mouse button

40 details += " with center mouse button";

41 else // left mouse button

42 details += " with left mouse button";

43

44 statusBar.setText( details ); // display message in statusBar

45 } // end method mouseClicked

46 } // end private inner class MouseClickHandler

47 } // end class MouseDetailsFrame

Page 233: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

233

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseDetails.java

(1 of 2)

1 // Fig. 11.32: MouseDetails.java

2 // Testing MouseDetailsFrame.

3 import javax.swing.JFrame;

4

5 public class MouseDetails

6 {

7 public static void main( String args[] )

8 {

9 MouseDetailsFrame mouseDetailsFrame = new MouseDetailsFrame();

10 mouseDetailsFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 mouseDetailsFrame.setSize( 400, 150 ); // set frame size

12 mouseDetailsFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class MouseDetails

Page 234: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

234

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

MouseDetails.java

(2 of 2)

Page 235: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

235

1992-2007 Pearson Education, Inc. All rights reserved.

import java.awt.BorderLayout;import java.awt.Graphics;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JFrame;import javax.swing.JLabel;

public class MouseDetailsFrame extends JFrame { private String details; // String representing private JLabel statusBar; // JLabel that appears at bottom of window

// constructor sets title bar String and register mouse listener public MouseDetailsFrame() { super( "Mouse clicks and buttons" ); statusBar = new JLabel( "Click the mouse" ); add( statusBar, BorderLayout.SOUTH ); addMouseListener( new MouseClickHandler() ); // add handler } // end MouseDetailsFrame constructor

Page 236: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

236

1992-2007 Pearson Education, Inc. All rights reserved.

// inner class to handle mouse events private class MouseClickHandler extends MouseAdapter {// handle mouse click event and determine which button was pressed public void mouseClicked( MouseEvent event ) { int xPos = event.getX(); // get x position of mouse int yPos = event.getY(); // get y position of mouse

details = String.format( "Clicked %d time(s)", event.getClickCount() );

if ( event.isMetaDown() ) // right mouse button

details += " with right mouse button"; else if ( event.isAltDown() ) // middle mouse button details += " with center mouse button"; else // left mouse button details += " with left mouse button";

statusBar.setText( details ); // display message in statusBar } // end method mouseClicked } // end private inner class MouseClickHandler} // end class MouseDetailsFrame

Page 237: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

237

1992-2007 Pearson Education, Inc. All rights reserved.

11.15 JPanel Subclass for Drawing with the Mouse

• Overriding class JPanel– Provides a dedicated drawing area

Page 238: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

238

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.33 | InputEvent methods that help distinguish among left-, center- and right-mouse-button clicks.

InputEvent method Description

isMetaDown() Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mouse-button click on a one-button mouse, the user can hold down the

Meta key on the keyboard and click the mouse button.

isAltDown() Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mouse-button click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively.

Page 239: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

239

1992-2007 Pearson Education, Inc. All rights reserved.

Method paintComponent

• Method paintComponent– Draws on a Swing component

– Overriding method allows you to create custom drawings

– Must call superclass method first when overridden

Page 240: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

240

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.13

Most Swing GUI components can be transparent or opaque. If a Swing GUI component is opaque, its background will be cleared when its paintComponent method is called. Only opaque components can display a customized background color. JPanel objects are opaque by default.

Page 241: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

241

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 11.1

In a JComponent subclass’s paintComponent method, the first statement should always be a call to the superclass’s paintComponent method to ensure that an object of the subclass displays correctly.

Page 242: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

242

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.5

If an overridden paintComponent method does not call the superclass’s version, the subclass component may not display properly. If an overridden paintComponent method calls the superclass’s version after other drawing is performed, the drawing will be erased.

Page 243: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

243

1992-2007 Pearson Education, Inc. All rights reserved.

Defining the Custom Drawing Area

• Customized subclass of JPanel– Provides custom drawing area

– Class Graphics is used to draw on Swing components

– Class Point represents an x-y coordinate

Page 244: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

244

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PaintPanel.java

(1 of 2)

1 // Fig. 11.34: PaintPanel.java

2 // Using class MouseMotionAdapter.

3 import java.awt.Point;

4 import java.awt.Graphics;

5 import java.awt.event.MouseEvent;

6 import java.awt.event.MouseMotionAdapter;

7 import javax.swing.JPanel;

8

9 public class PaintPanel extends JPanel

10 {

11 private int pointCount = 0; // count number of points

12

13 // array of 10000 java.awt.Point references

14 private Point points[] = new Point[ 10000 ];

15

16 // set up GUI and register mouse event handler

17 public PaintPanel()

18 {

19 // handle frame mouse motion event

20 addMouseMotionListener(

21

Create array of Points

Page 245: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

245

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PaintPanel.java

(2 of 2)

22 new MouseMotionAdapter() // anonymous inner class

23 {

24 // store drag coordinates and repaint

25 public void mouseDragged( MouseEvent event )

26 {

27 if ( pointCount < points.length )

28 {

29 points[ pointCount ] = event.getPoint(); // find point

30 pointCount++; // increment number of points in array

31 repaint(); // repaint JFrame

32 } // end if

33 } // end method mouseDragged

34 } // end anonymous inner class

35 ); // end call to addMouseMotionListener

36 } // end PaintPanel constructor

37

38 // draw oval in a 4-by-4 bounding box at specified location on window

39 public void paintComponent( Graphics g )

40 {

41 super.paintComponent( g ); // clears drawing area

42

43 // draw all points in array

44 for ( int i = 0; i < pointCount; i++ )

45 g.fillOval( points[ i ].x, points[ i ].y, 4, 4 );

46 } // end method paintComponent

47 } // end class PaintPanel

Anonymous inner class for event handling

Override mouseDragged method

Get location of mouse cursor

Repaint the JFrame

Get the x and y-coordinates of the Point

Page 246: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

246

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.14

Calling repaint for a Swing GUI component indicates that the component should be refreshed on the screen as soon as possible. The background of the GUI component is cleared only if the component is opaque. JComponent method setOpaque can be passed a boolean argument indicating whether the component is opaque (true) or transparent (false).

Page 247: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

247

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.15

Drawing on any GUI component is performed with coordinates that are measured from the upper-left corner (0, 0) of that GUI component, not the upper-left corner of the screen.

Page 248: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

248

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Painter.java

(1 of 2)

1 // Fig. 11.35: Painter.java

2 // Testing PaintPanel.

3 import java.awt.BorderLayout;

4 import javax.swing.JFrame;

5 import javax.swing.JLabel;

6

7 public class Painter

8 {

9 public static void main( String args[] )

10 {

11 // create JFrame

12 JFrame application = new JFrame( "A simple paint program" );

13

14 PaintPanel paintPanel = new PaintPanel(); // create paint panel

15 application.add( paintPanel, BorderLayout.CENTER ); // in center

16

17 // create a label and place it in SOUTH of BorderLayout

18 application.add( new JLabel( "Drag the mouse to draw" ),

19 BorderLayout.SOUTH );

20

21 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

22 application.setSize( 400, 200 ); // set frame size

23 application.setVisible( true ); // display frame

24 } // end main

25 } // end class Painter

Create instance of custom drawing panel

Page 249: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

249

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Painter.java

(2 of 2)

Page 250: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

250

1992-2007 Pearson Education, Inc. All rights reserved.

11.16 Key-Event Handling

•KeyListener interface– For handling KeyEvents

– Declares methods keyPressed, keyReleased and keyTyped

Page 251: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

251

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

KeyDemoFrame.java

(1 of 3)

3 import java.awt.Color;

4 import java.awt.event.KeyListener;

5 import java.awt.event.KeyEvent;

6 import javax.swing.JFrame;

7 import javax.swing.JTextArea;

8

9 public class KeyDemoFrame extends JFrame implements KeyListener

10 {

11 private String line1 = ""; // first line of textarea

12 private String line2 = ""; // second line of textarea

13 private String line3 = ""; // third line of textarea

14 private JTextArea textArea; // textarea to display output

15

16 // KeyDemoFrame constructor

17 public KeyDemoFrame()

18 {

19 super( "Demonstrating Keystroke Events" );

20

21 textArea = new JTextArea( 10, 15 ); // set up JTextArea

22 textArea.setText( "Press any key on the keyboard..." );

23 textArea.setEnabled( false ); // disable textarea

24 textArea.setDisabledTextColor( Color.BLACK ); // set text color

25 add( textArea ); // add textarea to JFrame

26

27 addKeyListener( this ); // allow frame to process key events

28 } // end KeyDemoFrame constructor

29

Page 252: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

252

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

KeyDemoFrame.java

(2 of 3)

30 // handle press of any key

31 public void keyPressed( KeyEvent event )

32 {

33 line1 = String.format( "Key pressed: %s",

34 event.getKeyText( event.getKeyCode() ) ); // output pressed key

35 setLines2and3( event ); // set output lines two and three

36 } // end method keyPressed

37

38 // handle release of any key

39 public void keyReleased( KeyEvent event )

40 {

41 line1 = String.format( "Key released: %s",

42 event.getKeyText( event.getKeyCode() ) ); // output released key

43 setLines2and3( event ); // set output lines two and three

44 } // end method keyReleased

45

46 // handle press of an action key

47 public void keyTyped( KeyEvent event )

48 {

49 line1 = String.format( "Key typed: %s", event.getKeyChar() );

50 setLines2and3( event ); // set output lines two and three

51 } // end method keyTyped

52

Page 253: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

253

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

KeyDemoFrame.java

(3 of 3)

53 // set second and third lines of output

54 private void setLines2and3( KeyEvent event )

55 {

56 line2 = String.format( "This key is %san action key",

57 ( event.isActionKey() ? "" : "not " ) );

58

59 String temp = event.getKeyModifiersText( event.getModifiers() );

60

61 line3 = String.format( "Modifier keys pressed: %s",

62 ( temp.equals( "" ) ? "none" : temp ) ); // output modifiers

63

64 textArea.setText( String.format( "%s\n%s\n%s\n",

65 line1, line2, line3 ) ); // output three lines of text

66 } // end method setLines2and3

67 } // end class KeyDemoFrame

Page 254: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

254

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

KeyDemo.java

(1 of 2)

1 // Fig. 11.37: KeyDemo.java

2 // Testing KeyDemoFrame.

3 import javax.swing.JFrame;

4

5 public class KeyDemo

6 {

7 public static void main( String args[] )

8 {

9 KeyDemoFrame keyDemoFrame = new KeyDemoFrame();

10 keyDemoFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 keyDemoFrame.setSize( 350, 100 ); // set frame size

12 keyDemoFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class KeyDemo

Page 255: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

255

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

KeyDemo.java

(1 of 2)

Page 256: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

256

1992-2007 Pearson Education, Inc. All rights reserved.

import java.awt.Color;import java.awt.event.KeyListener;import java.awt.event.KeyEvent;import javax.swing.JFrame;import javax.swing.JTextArea;

public class KeyDemoFrame extends JFrame implements KeyListener {

private String line1 = ""; // first line of textarea private String line2 = ""; // second line of textarea private String line3 = ""; // third line of textarea private JTextArea textArea; // textarea to display output

Page 257: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

257

1992-2007 Pearson Education, Inc. All rights reserved.

// KeyDemoFrame constructor public KeyDemoFrame() { super( "Demonstrating Keystroke Events" );

textArea = new JTextArea( 10, 15 ); // set up JTextArea textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); // disable textarea textArea.setDisabledTextColor( Color.BLACK ); // set text color add( textArea ); // add textarea to JFrame

addKeyListener( this ); // allow frame to process key event

} // end KeyDemoFrame constructor

Page 258: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

258

1992-2007 Pearson Education, Inc. All rights reserved.

// handle press of any key public void keyPressed( KeyEvent event ) { line1 = String.format( "Key pressed: %s",

event.getKeyText( event.getKeyCode() ) ); // output pressed key setLines2and3( event ); // set output lines two and three

} // end method keyPressed

// handle release of any key public void keyReleased( KeyEvent event ) { line1 = String.format( "Key released: %s",

event.getKeyText( event.getKeyCode() ) ); // output released key setLines2and3( event ); // set output lines two and three

} // end method keyReleased

// handle press of an action key public void keyTyped( KeyEvent event ) { line1 = String.format( "Key typed: %s", event.getKeyChar() );

setLines2and3( event ); // set output lines two and three } // end method keyTyped

Page 259: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

259

1992-2007 Pearson Education, Inc. All rights reserved.

// set second and third lines of output private void setLines2and3( KeyEvent event ) { line2 = String.format( "This key is %san action key", ( event.isActionKey() ? "" : "not " ) );

String temp = event.getKeyModifiersText( event.getModifiers() );

line3 = String.format( "Modifier keys pressed: %s", ( temp.equals( "" ) ? "none" : temp ) ); // output modifiers

textArea.setText( String.format( "%s\n%s\n%s\n", line1, line2, line3 ) ); // output three lines of text

} // end method setLines2and3} // end class KeyDemoFrame

Page 260: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

260

1992-2007 Pearson Education, Inc. All rights reserved.

11.17 Layout Managers

• Layout managers– Provided to arrange GUI components in a container

– Provide basic layout capabilities

– Implement the interface LayoutManager

– class Container’s setLayout method takes an object that imlements the LayoutManager interface

Page 261: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

261

1992-2007 Pearson Education, Inc. All rights reserved.

11.17 Layout Managers

• There are three ways to arrange components – Absolute possitioning:

• Setting Container’s layout to null

• Coordinates of the component with respect to the upper left possition of the container

• Specify the size of the component as well

– Layout Managers:• Easier then (1) but

• Lose some contro – size or possitioning

– Visual programming in an IDe:

Page 262: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

262

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.16

Most Java programming environments provide GUI design tools that help a programmer graphically design a GUI; the design tools then write the Java code to create the GUI. Such tools often provide greater control over the size, position and alignment of GUI components than do the built-in layout managers.

Page 263: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

263

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.17

It is possible to set a Container’s layout to null, which indicates that no layout manager should be used. In a Container without a layout manager, the programmer must position and size the components in the given container and take care that, on resize events, all components are repositioned as necessary. A component’s resize events can be processed by a ComponentListener.

Page 264: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

264

1992-2007 Pearson Education, Inc. All rights reserved.

11.17.1 FlowLayout

•FlowLayout– Simplest layout manager

– Components are placed left to right in the order they are added

– Components can be left aligned, centered or right aligned

Page 265: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

265

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 11.38 | Layout managers.

Layout manager Description

FlowLayout Default for javax.swing.JPanel. Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the Container method add, which takes a Component and an integer index position as arguments.

BorderLayout Default for JFrames (and other windows). Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER.

GridLayout Arranges the components into rows and columns.

Page 266: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

266

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutFrame.java

(1 of 3)

1 // Fig. 11.39: FlowLayoutFrame.java

2 // Demonstrating FlowLayout alignments.

3 import java.awt.FlowLayout;

4 import java.awt.Container;

5 import java.awt.event.ActionListener;

6 import java.awt.event.ActionEvent;

7 import javax.swing.JFrame;

8 import javax.swing.JButton;

9

10 public class FlowLayoutFrame extends JFrame

11 {

12 private JButton leftJButton; // button to set alignment left

13 private JButton centerJButton; // button to set alignment center

14 private JButton rightJButton; // button to set alignment right

15 private FlowLayout layout; // layout object

16 private Container container; // container to set layout

17

18 // set up GUI and register button listeners

19 public FlowLayoutFrame()

20 {

21 super( "FlowLayout Demo" );

22

23 layout = new FlowLayout(); // create FlowLayout

24 container = getContentPane(); // get container to layout

25 setLayout( layout ); // set frame layout

26

Page 267: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

267

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutFrame.java

(2 of 3)

27 // set up leftJButton and register listener

28 leftJButton = new JButton( "Left" ); // create Left button

29 add( leftJButton ); // add Left button to frame

30 leftJButton.addActionListener(

31

32 new ActionListener() // anonymous inner class

33 {

34 // process leftJButton event

35 public void actionPerformed( ActionEvent event )

36 {

37 layout.setAlignment( FlowLayout.LEFT );

38

39 // realign attached components

40 layout.layoutContainer( container );

41 } // end method actionPerformed

42 } // end anonymous inner class

43 ); // end call to addActionListener

Page 268: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

268

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutFrame.java

(2 of 3)

45 // set up centerJButton and register listener

46 centerJButton = new JButton( "Center" ); // create Center button

47 add( centerJButton ); // add Center button to frame

48 centerJButton.addActionListener(

49

50 new ActionListener() // anonymous inner class

51 {

52 // process centerJButton event

53 public void actionPerformed( ActionEvent event )

54 {

55 layout.setAlignment( FlowLayout.CENTER );

57 // realign attached components

58 layout.layoutContainer( container );

59 } // end method actionPerformed

60 } // end anonymous inner class

61 ); // end call to addActionListener

Page 269: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

269

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutFrame.java

(3 of 3)

63 // set up rightJButton and register listener

64 rightJButton = new JButton( "Right" ); // create Right button

65 add( rightJButton ); // add Right button to frame

66 rightJButton.addActionListener(

67

68 new ActionListener() // anonymous inner class

69 {

70 // process rightJButton event

71 public void actionPerformed( ActionEvent event )

72 {

73 layout.setAlignment( FlowLayout.RIGHT );

74

75 // realign attached components

76 layout.layoutContainer( container );

77 } // end method actionPerformed

78 } // end anonymous inner class

79 ); // end call to addActionListener

80 } // end FlowLayoutFrame constructor

81 } // end class FlowLayoutFrame

Page 270: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

270

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutDemo.java

(1 of 2)

1 // Fig. 11.40: FlowLayoutDemo.java

2 // Testing FlowLayoutFrame.

3 import javax.swing.JFrame;

4

5 public class FlowLayoutDemo

6 {

7 public static void main( String args[] )

8 {

9 FlowLayoutFrame flowLayoutFrame = new FlowLayoutFrame();

10 flowLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 flowLayoutFrame.setSize( 300, 75 ); // set frame size

12 flowLayoutFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class FlowLayoutDemo

Page 271: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

271

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

FlowLayoutDemo.java

(2 of 2)

Page 272: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

272

1992-2007 Pearson Education, Inc. All rights reserved.

11.17.2 BorderLayout

•BorderLayout• Arranges components into five regions – north,

south, east, west and center

• Implements interface LayoutManager2– A subinterface of LayoutManager

• Provides horizontal gap spacing and vertical gap spacing

– Constructor:

– BorderLayour(int hgap, int vgap);

Page 273: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

273

1992-2007 Pearson Education, Inc. All rights reserved.

Example: Border Layout

• Enter two integers to two distinct textFields

• when pressed + button calcuate and display the sum as a label

• Components:– north: title - JLabel

– west: first textField - jTextField

– east: second testField - JTEextField

– center: addition button -JButton

– south: result apears - JLabel

Page 274: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

274

1992-2007 Pearson Education, Inc. All rights reserved.

Test class

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.swing.event.*;public class Border0 { public static void main(String[] args){ BorderFrame0 borderFrame0 = new BorderFrame0(); borderFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); borderFrame0.setSize(400, 200); borderFrame0.setVisible(true);}

}

Page 275: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

275

1992-2007 Pearson Education, Inc. All rights reserved.

class BorderFrame0

class BorderFrame0 extends JFrame {

private JLabel title;private JLabel result;private JButton addition;private JTextField first;private JTextField second;

public BorderFrame0() {

setLayout(new BorderLayout(10,10));title = new JLabel("Adding two integers");result = new JLabel(" ");addition = new JButton("+");first = new JTextField(10);second = new JTextField(10);

Page 276: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

276

1992-2007 Pearson Education, Inc. All rights reserved.

class BorderFrame0 (cont.)

add(title,BorderLayout.NORTH);add(addition,BorderLayout.CENTER);add(first,BorderLayout.WEST);add(second,BorderLayout.EAST);add(result,BorderLayout.SOUTH);

ButtonHandler handler = new ButtonHandler();

addition.addActionListener(handler);

} // end constructor

Page 277: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

277

1992-2007 Pearson Education, Inc. All rights reserved.

inner class ButtonHandler

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {

int a,b,sum; if(e.getSource() == addition) { a = Integer.parseInt(first.getText()); b = Integer.parseInt(second.getText()); sum = a+b; result.setText(""+a+" + "+b+" = "+sum); } // end if

} // end method actionPerformed } // end inner class ButtonHandler

} // end class GridFrame0

Page 278: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

278

1992-2007 Pearson Education, Inc. All rights reserved.

output of program

Page 279: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

279

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.18

Each container can have only one layout manager. Separate containers in the same application can use different layout managers.

Page 280: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

280

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.19

If no region is specified when adding a Component to a BorderLayout, the layout manager assumes that the Component should be added to region BorderLayout.CENTER.

Page 281: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

281

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 11.6

When more than one component is added to a region in a BorderLayout, only the last component added to that region will be displayed. There is no error that indicates this problem.

Page 282: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

282

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BorderLayoutFrame.java

(1 of 2)

1 // Fig. 11.41: BorderLayoutFrame.java

2 // Demonstrating BorderLayout.

3 import java.awt.BorderLayout;

4 import java.awt.event.ActionListener;

5 import java.awt.event.ActionEvent;

6 import javax.swing.JFrame;

7 import javax.swing.JButton;

8

9 public class BorderLayoutFrame extends JFrame implements ActionListener

10 {

11 private JButton buttons[]; // array of buttons to hide portions

12 private final String names[] = { "Hide North", "Hide South",

13 "Hide East", "Hide West", "Hide Center" };

14 private BorderLayout layout; // borderlayout object

15

Page 283: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

283

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BorderLayoutFrame.java

(1 of 2)

16 // set up GUI and event handling

17 public BorderLayoutFrame()

18 {

19 super( "BorderLayout Demo" );

20

21 layout = new BorderLayout( 5, 5 ); // 5 pixel gaps

22 setLayout( layout ); // set frame layout

23 buttons = new JButton[ names.length ]; // set size of array

24

25 // create JButtons and register listeners for them

26 for ( int count = 0; count < names.length; count++ )

27 {

28 buttons[ count ] = new JButton( names[ count ] );

29 buttons[ count ].addActionListener( this );

30 } // end for

Page 284: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

284

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BorderLayoutFrame.java

(2 of 2)

31

32 add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north

33 add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south

34 add( buttons[ 2 ], BorderLayout.EAST ); // add button to east

35 add( buttons[ 3 ], BorderLayout.WEST ); // add button to west

36 add( buttons[ 4 ], BorderLayout.CENTER ); // add button to center

37 } // end BorderLayoutFrame constructor

38

39 // handle button events

40 public void actionPerformed( ActionEvent event )

41 {

42 // check event source and layout content pane correspondingly

43 for ( JButton button : buttons )

44 {

45 if ( event.getSource() == button )

46 button.setVisible( false ); // hide button clicked

47 else

48 button.setVisible( true ); // show other buttons

49 } // end for

50

51 layout.layoutContainer( getContentPane() ); // layout content pane

52 } // end method actionPerformed

53 } // end class BorderLayoutFrame

Page 285: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

285

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BorderLayoutDemo.java

(1 of 2)

1 // Fig. 11.42: BorderLayoutDemo.java

2 // Testing BorderLayoutFrame.

3 import javax.swing.JFrame;

4

5 public class BorderLayoutDemo

6 {

7 public static void main( String args[] )

8 {

9 BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame();

10 borderLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 borderLayoutFrame.setSize( 300, 200 ); // set frame size

12 borderLayoutFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class BorderLayoutDemo

horizontal gap vertical gap

Page 286: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

286

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BorderLayoutDemo.java

(2 of 2)

Page 287: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

287

1992-2007 Pearson Education, Inc. All rights reserved.

11.17.3 GridLayout

•GridLayout• Divides container into a grid

• Every component has the same width and height

• Constructors– GridLayout(int raws,int columns);

– GridLayout(int raws,int columns,int hgap, int vgap);

Page 288: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

288

1992-2007 Pearson Education, Inc. All rights reserved.

Example:GridLayour

• Create a GridLayout with 3 raws and 2 columns

• Enter name and lastname of a person

• when pressed OK, process these strings

• when pressed Cancel, erase these fields

Page 289: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

289

1992-2007 Pearson Education, Inc. All rights reserved.

Test Class

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.swing.event.*;public class GridLayout0 {public static void main(String[] args){

GridFrame0 gridFrame0 = new GridFrame0();

gridFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

gridFrame0.setSize(400, 200);gridFrame0.setVisible(true);}

}

Page 290: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

290

1992-2007 Pearson Education, Inc. All rights reserved.

class GridFrame0

class GridFrame0 extends JFrame {

private JLabel name;private JLabel lastName;

private JTextField nameText; private JTextField lastNameText;

private JButton ok;private JButton cancel;

Page 291: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

291

1992-2007 Pearson Education, Inc. All rights reserved.

class GridFrame0 (cont.)

public GridFrame0() {

setLayout(new GridLayout(3,2,5,5));name = new JLabel("Name");lastName = new JLabel("Last Name");ok = new JButton("OK");cancel = new JButton("Cancel");nameText = new JTextField(10);lastNameText = new JTextField(20);add(name);add(nameText);add(lastName);add(lastNameText);add(ok);add(cancel);

ButtonHandler handler = new ButtonHandler();ok.addActionListener(handler);cancel.addActionListener(handler);

} // end constructor

Page 292: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

292

1992-2007 Pearson Education, Inc. All rights reserved.

inner class ButtonHanler

private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == ok)

System.out.println(nameText.getText()+ ""+lastNameText.getText()); if(e.getSource() == cancel) {

nameText.setText(""); lastNameText.setText("");

} // end if } // end method actionPerformed

} // end inner class ButtonHandler} // end class GridFrame0

Page 293: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

293

1992-2007 Pearson Education, Inc. All rights reserved.

Page 294: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

294

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GridLayoutFrame.java

(1 of 2)

1 // Fig. 11.43: GridLayoutFrame.java

2 // Demonstrating GridLayout.

3 import java.awt.GridLayout;

4 import java.awt.Container;

5 import java.awt.event.ActionListener;

6 import java.awt.event.ActionEvent;

7 import javax.swing.JFrame;

8 import javax.swing.JButton;

9

10 public class GridLayoutFrame extends JFrame implements ActionListener

11 {

12 private JButton buttons[]; // array of buttons

13 private final String names[] =

14 { "one", "two", "three", "four", "five", "six" };

15 private boolean toggle = true; // toggle between two layouts

16 private Container container; // frame container

17 private GridLayout gridLayout1; // first gridlayout

18 private GridLayout gridLayout2; // second gridlayout

Page 295: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

295

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GridLayoutFrame.java

(1 of 2)

20 // no-argument constructor

21 public GridLayoutFrame()

22 {

23 super( "GridLayout Demo" );

24 gridLayout1 = new GridLayout( 2, 3, 5, 5 ); // 2 by 3; gaps of 5

25 gridLayout2 = new GridLayout( 3, 2 ); // 3 by 2; no gaps

26 container = getContentPane(); // get content pane

27 setLayout( gridLayout1 ); // set JFrame layout

28 buttons = new JButton[ names.length ]; // create array of JButtons

29

Page 296: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

296

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GridLayoutFrame.java

(2 of 2)

30 for ( int count = 0; count < names.length; count++ )

31 {

32 buttons[ count ] = new JButton( names[ count ] );

33 buttons[ count ].addActionListener( this ); // register listener

34 add( buttons[ count ] ); // add button to JFrame

35 } // end for

36 } // end GridLayoutFrame constructor

37

38 // handle button events by toggling between layouts

39 public void actionPerformed( ActionEvent event )

40 {

41 if ( toggle )

42 container.setLayout( gridLayout2 ); // set layout to second

43 else

44 container.setLayout( gridLayout1 ); // set layout to first

45

46 toggle = !toggle; // set toggle to opposite value

47 container.validate(); // re-layout container

48 } // end method actionPerformed

49 } // end class GridLayoutFrame

Page 297: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

297

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GridLayoutDemo.java

1 // Fig. 11.44: GridLayoutDemo.java

2 // Testing GridLayoutFrame.

3 import javax.swing.JFrame;

4

5 public class GridLayoutDemo

6 {

7 public static void main( String args[] )

8 {

9 GridLayoutFrame gridLayoutFrame = new GridLayoutFrame();

10 gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 gridLayoutFrame.setSize( 300, 200 ); // set frame size

12 gridLayoutFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class GridLayoutDemo

Page 298: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

298

1992-2007 Pearson Education, Inc. All rights reserved.

11.18 Using Panels to Manage More Complex Layouts

• Complex GUIs often require multiple panels to arrange their components properly

Page 299: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

299

1992-2007 Pearson Education, Inc. All rights reserved.

Example Panels

• Entering and processing nemes and lastnames using panels

Page 300: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

300

1992-2007 Pearson Education, Inc. All rights reserved.

Test class

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.swing.event.*;public class Panel1 {public static void main(String[] args){GridFrame1 gridFrame1 = new GridFrame1(); gridFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);gridFrame1.setSize(400, 200);gridFrame1.setVisible(true);}

}

Page 301: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

301

1992-2007 Pearson Education, Inc. All rights reserved.

class GridFrame1

class GridFrame1 extends JFrame implements ActionListener {

private JLabel name;private JLabel lastName;private JTextField nameText;private JTextField lastNameText;private JButton ok;private JButton cancel;

// create three panels private JPanel topPanel;private JPanel midPanel;private JPanel butomPanel;

Page 302: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

302

1992-2007 Pearson Education, Inc. All rights reserved.

class GridFrame1 (cont.)

public GridFrame1() {

setLayout(new GridLayout(3,1,5,5));name = new JLabel("Name");lastName = new JLabel("Last Name");ok = new JButton("OK");cancel = new JButton("Cancel");nameText = new JTextField(10);lastNameText = new JTextField(20);topPanel = new JPanel();midPanel = new JPanel();butomPanel = new JPanel();

Page 303: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

303

1992-2007 Pearson Education, Inc. All rights reserved.

class GridFrame1 (cont.)

// add components to relevant panels topPanel.add(name);

topPanel.add(nameText);midPanel.add(lastName);midPanel.add(lastNameText);butomPanel.add(ok);butomPanel.add(cancel);

// add panels to the frame add(topPanel);

add(midPanel);add(butomPanel);

Page 304: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

304

1992-2007 Pearson Education, Inc. All rights reserved.

inner class ButtonHandler

ok.addActionListener(this); cancel.addActionListener(this);} // end constructor

public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) System.out.println(nameText.getText()+" "+lastNameText.getText()); if(e.getSource() == cancel) {

nameText.setText("");lastNameText.setText("");

} // end if } // end method actionPerformed } // end class GridFrame0

Page 305: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

305

1992-2007 Pearson Education, Inc. All rights reserved.

output

Page 306: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

306

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PanelFrame.java

(1 of 2)

1 // Fig. 11.45: PanelFrame.java

2 // Using a JPanel to help lay out components.

3 import java.awt.GridLayout;

4 import java.awt.BorderLayout;

5 import javax.swing.JFrame;

6 import javax.swing.JPanel;

7 import javax.swing.JButton;

8

9 public class PanelFrame extends JFrame

10 {

11 private JPanel buttonJPanel; // panel to hold buttons

12 private JButton buttons[]; // array of buttons

13

14 // no-argument constructor

15 public PanelFrame()

16 {

17 super( "Panel Demo" );

18 buttons = new JButton[ 5 ]; // create buttons array

19 buttonJPanel = new JPanel(); // set up panel

20 buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) );

21

Page 307: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

307

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PanelFrame.java

(2 of 2)

22 // create and add buttons

23 for ( int count = 0; count < buttons.length; count++ )

24 {

25 buttons[ count ] = new JButton( "Button " + ( count + 1 ) );

26 buttonJPanel.add( buttons[ count ] ); // add button to panel

27 } // end for

28

29 add( buttonJPanel, BorderLayout.SOUTH ); // add panel to JFrame

30 } // end PanelFrame constructor

31 } // end class PanelFrame

Page 308: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

308

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

PanelDemo.java

1 // Fig. 11.46: PanelDemo.java

2 // Testing PanelFrame.

3 import javax.swing.JFrame;

4

5 public class PanelDemo extends JFrame

6 {

7 public static void main( String args[] )

8 {

9 PanelFrame panelFrame = new PanelFrame();

10 panelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 panelFrame.setSize( 450, 200 ); // set frame size

12 panelFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class PanelDemo

Page 309: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

309

1992-2007 Pearson Education, Inc. All rights reserved.

Example Panels

• Add an action to the buttons

• when cliced a button display which one is cliced in a textField placed to the north

Page 310: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

310

1992-2007 Pearson Education, Inc. All rights reserved.

class PanelFrame0

class PanelFrame0 extends JFrame implements ActionListener {

private JPanel buttonJPanel; private JButton buttons[];private JTextField textField;

public PanelFrame0(){

buttons = new JButton[5];buttonJPanel = new JPanel();textField = new JTextField();buttonJPanel.setLayout(new GridLayout(1,buttons.length));for(int i = 0;i < buttons.length;i++){

buttons[i] = new JButton("Button"+(i+1));buttonJPanel.add(buttons[i]);

}

Page 311: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

311

1992-2007 Pearson Education, Inc. All rights reserved.

class PanelFrame0 (cont.)

add(buttonJPanel,BorderLayout.SOUTH);add(textField,BorderLayout.NORTH);

for(int i = 0;i < buttons.length;i++)buttons[i].addActionListener(this);

} // end constructor

Page 312: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

312

1992-2007 Pearson Education, Inc. All rights reserved.

inner class ButtonHandler

public void actionPerformed(ActionEvent e) { String str = ""; textField.setText(""); for(int i = 0;i < buttons.length;i++) {

if(e.getSource()==buttons[i]) str += "you clicked "+"Button"+(i+1);

textField.setText(str); } // end for

} // end method actionPerformed} // end class PanelFrame0

Page 313: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

313

1992-2007 Pearson Education, Inc. All rights reserved.

output of the program

Page 314: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

314

1992-2007 Pearson Education, Inc. All rights reserved.

11.19 JTextArea

•JTextArea– Provides an area for manipulating multiple lines of text

•Box container– Subclass of Container

– Uses a BoxLayout layout manager

Page 315: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

315

1992-2007 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 11.20

To provide line-wrapping functionality for a JTextArea, invoke JTextArea method setLine-Wrap with a true argument.

Page 316: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

316

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextAreaFrame.java

(1 of 2)

1 // Fig. 11.47: TextAreaFrame.java

2 // Copying selected text from one textarea to another.

3 import java.awt.event.ActionListener;

4 import java.awt.event.ActionEvent;

5 import javax.swing.Box;

6 import javax.swing.JFrame;

7 import javax.swing.JTextArea;

8 import javax.swing.JButton;

9 import javax.swing.JScrollPane;

10

11 public class TextAreaFrame extends JFrame

12 {

13 private JTextArea textArea1; // displays demo string

14 private JTextArea textArea2; // highlighted text is copied here

15 private JButton copyJButton; // initiates copying of text

16

17 // no-argument constructor

18 public TextAreaFrame()

19 {

20 super( "TextArea Demo" );

21 Box box = Box.createHorizontalBox(); // create box

22 String demo = "This is a demo string to\n" +

23 "illustrate copying text\nfrom one textarea to \n" +

24 "another textarea using an\nexternal event\n";

25

26 textArea1 = new JTextArea( demo, 10, 15 ); // create textarea1

27 box.add( new JScrollPane( textArea1 ) ); // add scrollpane

28

Page 317: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

317

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextAreaFrame.java

(2 of 2)

29 copyJButton = new JButton( "Copy >>>" ); // create copy button

30 box.add( copyJButton ); // add copy button to box

31 copyJButton.addActionListener(

32

33 new ActionListener() // anonymous inner class

34 {

35 // set text in textArea2 to selected text from textArea1

36 public void actionPerformed( ActionEvent event )

37 {

38 textArea2.setText( textArea1.getSelectedText() );

39 } // end method actionPerformed

40 } // end anonymous inner class

41 ); // end call to addActionListener

42

43 textArea2 = new JTextArea( 10, 15 ); // create second textarea

44 textArea2.setEditable( false ); // disable editing

45 box.add( new JScrollPane( textArea2 ) ); // add scrollpane

46

47 add( box ); // add box to frame

48 } // end TextAreaFrame constructor

49 } // end class TextAreaFrame

Page 318: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

318

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextAreaDemo.java

(1 of 2)

1 // Fig. 11.48: TextAreaDemo.java

2 // Copying selected text from one textarea to another.

3 import javax.swing.JFrame;

4

5 public class TextAreaDemo

6 {

7 public static void main( String args[] )

8 {

9 TextAreaFrame textAreaFrame = new TextAreaFrame();

10 textAreaFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

11 textAreaFrame.setSize( 425, 200 ); // set frame size

12 textAreaFrame.setVisible( true ); // display frame

13 } // end main

14 } // end class TextAreaDemo

Page 319: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

319

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

TextAreaDemo.java

(2 of 2)

Page 320: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

320

1992-2007 Pearson Education, Inc. All rights reserved.

JScrollPane Scrollbar Policies

•JScrollPane has scrollbar policies– Horizontal policies

• Always (HORIZONTAL_SCROLLBAR_ALWAYS)

• As needed (HORIZONTAL_SCROLLBAR_AS_NEEDED)

• Never (HORIZONTAL_SCROLLBAR_NEVER)

– Vertical policies• Always (VERTICAL_SCROLLBAR_ALWAYS)

• As needed (VERTICAL_SCROLLBAR_AS_NEEDED)

• Never (VERTICAL_SCROLLBAR_NEVER)

Page 321: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

321

1992-2007 Pearson Education, Inc. All rights reserved.

Null Layout Edample

Page 322: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

322

1992-2007 Pearson Education, Inc. All rights reserved.

Page 323: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

323

1992-2007 Pearson Education, Inc. All rights reserved.

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class OverAll3 {public static void main(String[] args) {

EmployeeFrame3 employeeFrame3 = new EmployeeFrame3();

employeeFrame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

employeeFrame3.setSize(600, 500);employeeFrame3.setVisible(true);

}}

Page 324: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

324

1992-2007 Pearson Education, Inc. All rights reserved.

class EmployeeFrame3 extends JFrame {

private JButton ok;private JButton cancel;

private JLabel name;private JLabel lastName;private JTextField empName;private JTextField empLName;private JTextArea status; private JPanel leftPanel;private JPanel centerPanel;private JPanel rightPanel;private JPanel typePanels[];

Page 325: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

325

1992-2007 Pearson Education, Inc. All rights reserved.

private JLabel commision;private JLabel sales;private JLabel wage;private JLabel hours;private JTextField empCommision;private JTextField empSales;private JTextField empWage;private JTextField empHours;private String types[] = {"Commision","Hourly","Salaried"};private JComboBox empType;private int selected=0;int i; // couter for loops

Page 326: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

326

1992-2007 Pearson Education, Inc. All rights reserved.

public EmployeeFrame3() { setLayout(null);

ok = new JButton("OK");cancel = new JButton("CANCEL");rightPanel= new JPanel();rightPanel.setLayout(null);rightPanel.setSize(200,200);rightPanel.setLocation(450,150);ok.setSize(100,50);ok.setLocation(0,0);rightPanel.add(ok);rightPanel.add(cancel);cancel.setSize(100,50);cancel.setLocation(0,100);add(rightPanel);

Page 327: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

327

1992-2007 Pearson Education, Inc. All rights reserved.

centerPanel= new JPanel();centerPanel.setSize(250,250);centerPanel.setLocation(200,100);centerPanel.setLayout(new

GridLayout(2,2,10,30));name = new JLabel("Employee Name");name.setLocation(0,0);name.setSize(80,20);lastName = new JLabel("Employee LastName");empName = new JTextField(10);empLName = new JTextField(10);centerPanel.add(name);centerPanel.add(empName);centerPanel.add(lastName);centerPanel.add(empLName);add(centerPanel);

Page 328: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

328

1992-2007 Pearson Education, Inc. All rights reserved.

// define and add status texarea

status = new JTextArea(5,30);

status.setLocation(50,350);

status.setSize(200,100);

add(status);

Page 329: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

329

1992-2007 Pearson Education, Inc. All rights reserved.

// define and add left paneltypeEmp = new JLabel("Emp Type:");empType = new JComboBox(types);

leftPanel = new JPanel();leftPanel.setSize(150,50);leftPanel.setLocation(10,40);leftPanel.setLayout(new

GridLayout(1,2,10,10));leftPanel.add(typeEmp);leftPanel.add(empType);add(leftPanel);

Page 330: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

330

1992-2007 Pearson Education, Inc. All rights reserved.

// create and edd typ panels typePanels = new JPanel[3];for(i=0;i<typePanels.length;i++) {//create

arry of panels typePanels[i] = new JPanel(); typePanels[i].setLayout(new

GridLayout(0,2,10,10)); typePanels[i].setSize(150,80); typePanels[i].setLocation(10,200); add(typePanels[i]); typePanels[i].setVisible(false);

} // end for loop

Page 331: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

331

1992-2007 Pearson Education, Inc. All rights reserved.

// define and add components for type panels commision = new JLabel("Commision:");

sales = new JLabel("Sales:");wage = new JLabel("Wage:");hours = new JLabel("Hours:");empCommision = new JTextField(10);empHours = new JTextField(10);empWage = new JTextField(10);empSales = new JTextField(10);

typePanels[0].add(commision);typePanels[0].add(empCommision);typePanels[0].add(sales); typePanels[0].add(empSales);

Page 332: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

332

1992-2007 Pearson Education, Inc. All rights reserved.

typePanels[1].add(hours);typePanels[1].add(empHours);typePanels[2].add(wage);typePanels[2].add(empWage);

typePanels[0].setVisible(true);

// registoring events to components ButtonHandler handler = new ButtonHandler();ok.addActionListener(handler);cancel.addActionListener(handler);empType.addActionListener(handler);

} // end constructor

Page 333: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

333

1992-2007 Pearson Education, Inc. All rights reserved.

Page 334: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

334

1992-2007 Pearson Education, Inc. All rights reserved.

private class ButtonHandler implements ActionListener {

int j; double x; public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) {

status.setText(""); status.append("\

nName :"+empName.getText()); status.append("\

nLastName:"+empLName.getText()); status.append("\nType :"+types[selected]);

Page 335: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

335

1992-2007 Pearson Education, Inc. All rights reserved.

switch(selected) {case 0: x=Double.parseDouble(empCommision.getText());

status.append("\nCom Rate:“ +String.format("%10.2f",x)); x=Double.parseDouble(empSales.getText();

status.append("\nSalary:"+String.format("%10.2f",x));break;

Page 336: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

336

1992-2007 Pearson Education, Inc. All rights reserved.

case 1:x=Double.parseDouble(empHours.getText());status.append("\nHourly Rate:"+String.format("%10.2f",x));break;

case 2:x=Double.parseDouble(empWage.getText());status.append("\nwage:"+String.format("%10.2f",x));break;

} // end switch

} // end if

Page 337: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

337

1992-2007 Pearson Education, Inc. All rights reserved.

if(e.getSource() == cancel) { empName.setText(""); empLName.setText(""); status.setText(""); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText("");} // end if

Page 338: 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

338

1992-2007 Pearson Education, Inc. All rights reserved.

if(e.getSource() == empType) { selected = empType.getSelectedIndex(); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText(""); for(j=0;j< typePanels.length;j++) if(j==selected)

typePanels[j].setVisible(true); else

typePanels[j].setVisible(false);

} // end if getSource

} // end method actionPerformed } // end inner class ButtonHandler} // end outer class