Chapter 12 - Basic Graphical User Interface Components Outline 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 Introduction Swing Overview JLabel Event Handling Model JTextField and JPasswordField 12.5.1 How Event Handling Works JButton JCheckBox and JRadioButton JComboBox JList Multiple-Selection Lists  2000

Download Report

Transcript Chapter 12 - Basic Graphical User Interface Components Outline 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 Introduction Swing Overview JLabel Event Handling Model JTextField and JPasswordField 12.5.1 How Event Handling Works JButton JCheckBox and JRadioButton JComboBox JList Multiple-Selection Lists  2000

Chapter 12 - Basic Graphical User
Interface Components
Outline
12.1
12.2
12.3
12.4
12.5
12.6
12.7
12.8
12.9
12.10
Introduction
Swing Overview
JLabel
Event Handling Model
JTextField and JPasswordField
12.5.1 How Event Handling Works
JButton
JCheckBox and JRadioButton
JComboBox
JList
Multiple-Selection Lists
 2000 Prentice Hall, Inc. All rights reserved.
1
Chapter 12 - Basic Graphical User
Interface Components
Outline
12.11
12.12
12.13
12.14
12.15
Mouse Event Handling
Adapter Classes
Keyboard Event Handling
Layout Managers
12.14.1 FlowLayout
12.14.2 BorderLayout
12.14.3 GridLayout
Panels
 2000 Prentice Hall, Inc. All rights reserved.
2
3
12.1 Introduction
• Graphical User Interface ("Goo-ee")
– Pictorial interface to a program
• Distinctive "look" and "feel"
– Different applications with consistent GUIs improve
productivity
• GUIs built from components
– Component: object with which user interacts
– Examples: Labels, Text fields, Buttons, Checkboxes
 2000 Prentice Hall, Inc. All rights reserved.
4
12.1 Introduction
• Example GUI: Netscape Communicator
Button
Label
 2000 Prentice Hall, Inc. All rights reserved.
Menu
Menu bar
Text
field
5
12.2 Swing Overview
• Swing GUI components
– Defined in package javax.swing
– Original GUI components from Abstract Windowing Toolkit
in java.awt
• Heavyweight components - rely on local platform's windowing
system for look and feel
– Swing components are lightweight
• Written in Java, not weighed down by complex GUI
capabilities of platform
• More portable than heavyweight components
– Swing components allow programmer to specify look and
feel
• Can change depending on platform
• Can be same across all platforms
 2000 Prentice Hall, Inc. All rights reserved.
6
12.2 Swing Overview
• Swing component inheritance hierarchy
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
• Component defines methods that can be used in its
subclasses (for example, paint and repaint)
• Container - collection of related components
– When using JFrames, attach components to the content
pane (a Container)
– Method add
• JComponent - superclass to most Swing components
• Much of a component's functionality inherited from these
classes
 2000 Prentice Hall, Inc. All rights reserved.
7
12.2 Swing Overview
• Some capabilities of subclasses of JComponent
– Pluggable look and feel
– Shortcut keys (mnemonics)
• Direct access to components through keyboard
– Common event handling
• If several components perform same actions
– Tool tips
• Description of component that appears when mouse over it
 2000 Prentice Hall, Inc. All rights reserved.
8
12.3 JLabel
• Labels
–
–
–
–
Provide text instructions on a GUI
Read-only text
Programs rarely change a label's contents
Class JLabel (subclass of JComponent)
• Methods
18
label1 = new JLabel( "Label with text" );
• Can declare label text in constructor
– myLabel.setToolTipText( "Text" )
• Displays "Text"in a tool tip when mouse over label
– myLabel.setText( "Text" )
– myLabel.getText()
 2000 Prentice Hall, Inc. All rights reserved.
9
12.3 JLabel
• Icon
– Object that implements interface Icon
– One class is ImageIcon (.gif and .jpeg images)
24
Icon bug = new ImageIcon( "bug1.gif" );
• Assumed same directory as program (more Chapter 16)
– Display an icon with setIcon method (of class JLabel)
33
label3.setIcon( bug );
• myLabel.setIcon( myIcon );
• myLabel.getIcon //returns current Icon
 2000 Prentice Hall, Inc. All rights reserved.
10
12.3 JLabel
• Alignment
– By default, text appears to right of image
– JLabel methods setHorizontalTextPosition
and setVerticalTextPosition
• Specify where text appears in label
• Use integer constants defined in interface SwingConstants
(javax.swing)
– SwingConstants.LEFT, RIGHT, BOTTOM,
CENTER
• Another JLabel constructor
– JLabel( "Text", ImageIcon,
Text_Alignment_CONSTANT)
 2000 Prentice Hall, Inc. All rights reserved.
11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 12.4: LabelTest.java
// Demonstrating the JLabel class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
1. import
1.1 Class Labeltest
(extends JFrame)
Create a Container object, to which we attach
JLabel objects (subclass of JComponent).
1.2 Declarations
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
public LabelTest()
{
super( "Testing JLabel" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
1.3 getContentPane
Initialize text in JLabel constructor.
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
c.add( label1 );
2. Initialize JLabels
2.1 setToolTipText
Set the tool tip text, and attach
component to Container c.
Create a new ImageIcon (assumed to be
in same directory as program). More
Chapter 16.
// JLabel constructor with string, Icon and
// alignment arguments
Icon bug = new ImageIcon( "bug1.gif" );
label2 = new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
c.add( label2 );
// JLabel constructor no arguments
 2000 Prentice Hall, Inc. All rights reserved.
Set ImageIcon and alignment
of text in JLabel constructor.
12
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 }
Outline
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
Use a no-argument constructor. Set
label3.setHorizontalTextPosition(
text, icon, and alignment 2.2
using
SwingConstants.CENTER );
methods.
label3.setVerticalTextPosition(
setHorizontalText
SwingConstants.BOTTOM );
Position
label3.setToolTipText( "This is label3" );
c.add( label3 );
setSize( 275, 170 );
show();
}
2.3 setVerticalText
Position
2.3 setToolTipText
public static void main( String args[] )
{
LabelTest app = new LabelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
 2000 Prentice Hall, Inc. All rights reserved.
3. main
13
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
14
12.4 Event Handling Model
• GUIs are event driven
– Generate events when user interacts with GUI
• Mouse movements, mouse clicks, typing in a text field, etc.
– Event information stored in object that extends AWTEvent
• To process an event
– Register an event listener
• Object from a class that implements an event-listener interface
(from java.awt.event or javax.swing.event)
• "Listens" for events
– Implement event handler
• Method called in response to event
• Event handling interface has one or more methods that must be
defined
 2000 Prentice Hall, Inc. All rights reserved.
15
12.4 Event Handling Model
• Delegation event model
– Use of event listeners in event handling
– Processing of event delegated to particular object
• When an event occurs
– GUI component notifies its listeners
• Calls listener's event handling method
• Example:
– Enter pressed in a JTextField
– Method actionPerformed called for registered listener
– Details in following sections
 2000 Prentice Hall, Inc. All rights reserved.
16
12.5 JTextField and JPasswordField
• JTextFields and JPasswordFields
– Single line areas in which text can be entered or displayed
– JPasswordFields show inputted text as an asterisk *
– JTextField extends JTextComponent
• JPasswordField extends JTextField
• When Enter pressed
– ActionEvent occurs
– Currently active field "has the focus"
 2000 Prentice Hall, Inc. All rights reserved.
17
12.5 JTextField and JPasswordField
• Methods
– Constructors
• JTextField( 10 )
– Textfield with 10 columns of text
– Takes average character width, multiplies by 10
• JTextField( "Hi" )
– Sets text, width determined automatically
• JTextField( "Hi", 20 )
– setEditable( boolean )
• If false, user cannot edit text
• Can still generate events
– getPassword
• Class JPasswordField
• Returns password as an array of type char
 2000 Prentice Hall, Inc. All rights reserved.
18
12.5 JTextField and JPasswordField
• Class ActionEvent
– Method getActionCommand
• Returns text in JTextField that generated event
– Method getSource
• getSource returns Component reference
• Example
– Create JTextFields and a JPasswordField
– Create and register an event handler
• Use getSource to determine which component had event
• Display a dialog box when Enter pressed
 2000 Prentice Hall, Inc. All rights reserved.
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 12.7: TextFieldTest.java
// Demonstrating the JTextField class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. import
public class TextFieldTest extends JFrame {
private JTextField text1, text2, text3;
private JPasswordField password;
1.1 Declarations
1.2 Constructor
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
// construct textfield with default sizing
text1 = new JTextField( 10 );
c.add( text1 );
1.3 GUI components
Initialize text fields
Create new2.
JTextField
objects using the various
constructors.
2.1 setEditable
// construct textfield with default text
This text field cannot be modified
text2 = new JTextField( "Enter text here" );
a gray background). It can still
c.add( text2 );
generate events.
// construct textfield with default text and
// 20 visible elements and no event handler
text3 = new JTextField( "Uneditable text field", 20 );
text3.setEditable( false );
c.add( text3 );
 2000 Prentice Hall, Inc. All rights reserved.
(has
20
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// construct textfield with default text
password = new JPasswordField( "Hidden text" );
c.add( password );
Outline
2.2 JPasswordField
JPasswordField
initialized with
= new TextFieldHandler();
text, which appears as asterisks.
handler );
2.3 Event handler
handler );
TextFieldHandler handler
text1.addActionListener(
text2.addActionListener(
text3.addActionListener( handler );
password.addActionListener( handler );
setSize( 325, 100 );
show();
}
3. main
Register event handlers. Good
practice to use an inner class as an
event handler.
public static void main( String args[] )
{
TextFieldTest app = new TextFieldTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
// inner class for event handling
 2000 Prentice Hall, Inc. All rights reserved.
21
61
private class TextFieldHandler implements ActionListener {
62
public void actionPerformed( ActionEvent e )
63
{
64
String s = "";
65
66
if ( e.getSource() == text1 )
67
s = "text1: " + e.getActionCommand();
68
4. Inner class
TextFieldHandler
(event handler)
else if ( e.getSource() == text2 )
69
s = "text2: " + e.getActionCommand();
70
else if ( e.getSource() == text3 )
71
s = "text3: " + e.getActionCommand();
72
else if ( e.getSource() == password ) {
73
4.1 getSource
Use getActionCommand
to
get the text in the text field that
had the event. 4.2
getActionCommand
JPasswordField pwd =
74
(JPasswordField) e.getSource();
75
4.3 Downcast
reference
pwd.getPassword()
);
e.getSource()
returns a Component
reference, which is cast to a
JPasswordField.
s = "password: " +
76
new String(
77
}
78
79
JOptionPane.showMessageDialog( null, s );
80
81
Outline
}
}
82 }
 2000 Prentice Hall, Inc. All rights reserved.
22
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
23
12.5.1
How Event Handling Works
• Registering event listeners
– All JComponents contain an object of class
EventListenerList called listenerList
– When text1.addActionListener( handler )
executes
• New entry placed into listenerList
• Handling events
– When event occurs, has an event ID
• Component uses this to decide which method to call
• If ActionEvent, then actionPerformed called (in all
registered ActionListeners)
 2000 Prentice Hall, Inc. All rights reserved.
24
12.6 JButton
• Button
– Component user clicks to trigger an action
– Several types of buttons
• Command buttons, toggle buttons, check boxes, radio buttons
• Command button
– Generates ActionEvent when clicked
– Created with class JButton
• Inherits from class AbstractButton
• Defines many features of Swing buttons
• JButton
– Text on face called button label
– Each button should have a different label
– Can display Icons
 2000 Prentice Hall, Inc. All rights reserved.
25
12.6 JButton
• Methods of class JButton
– Constructors
JButton myButton = new JButton( "Label" );
JButton myButton = new JButton( "Label",
myIcon );
– setRolloverIcon( myIcon )
• Sets image to display when mouse over button
• Class ActionEvent
– getActionCommand
• Returns label of button that generated event
 2000 Prentice Hall, Inc. All rights reserved.
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 12.11: ButtonTest.java
// Creating JButtons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. import
public class ButtonTest extends JFrame {
private JButton plainButton, fancyButton;
1.1 Declarations
public ButtonTest()
{
super( "Testing Buttons" );
2. Initialize buttons and
Icons
Container c = getContentPane(); Create JButtons. Initialize
c.setLayout( new FlowLayout() ); with an ImageIcon.
// create buttons
plainButton = new JButton( "Plain Button" );
c.add( plainButton );
fancyButton
2.1 setRolloverIcon
2.2 Register event
handler
Icon bug1 = new ImageIcon( "bug1.gif" );
Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
c.add( fancyButton );
Set a different icon to appear when the
ButtonHandler
mouse is over the JButton.
// create an instance of inner class
// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
 2000 Prentice Hall, Inc. All rights reserved.
27
31
plainButton.addActionListener( handler );
32
33
setSize( 275, 100 );
34
show();
35
}
36
37
public static void main( String args[] )
38
{
39
ButtonTest app = new ButtonTest();
40
41
app.addWindowListener(
42
new WindowAdapter() {
43
public void windowClosing( WindowEvent e )
44
{
45
System.exit( 0 );
46
}
47
}
48
);
getActionCommand
49
}
that generated event.
50
51
// inner class for button event handling
52
private class ButtonHandler implements ActionListener {
53
public void actionPerformed( ActionEvent e )
54
{
55
JOptionPane.showMessageDialog( null,
56
"You pressed: " + e.getActionCommand() );
57
}
58
}
59 }
 2000 Prentice Hall, Inc. All rights reserved.
Outline
3. main
4. Inner class event
handler
returns label of button
28
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
29
12.7 JCheckBox and JRadioButton
• State buttons
– JToggleButton
• Subclasses JCheckBox, JRadioButton
– Have on/off (true/false) values
• Class JCheckBox
– Text appears to right of checkbox
– Constructor
JCheckBox myBox = new JCheckBox( "Title" );
 2000 Prentice Hall, Inc. All rights reserved.
30
12.7 JCheckBox and JRadioButton
• When JCheckBox changes
– ItemEvent generated
• Handled by an ItemListener, which must define
itemStateChanged
– Register handlers with with addItemListener
51
55
56
private class CheckBoxHandler implements ItemListener {
public void itemStateChanged( ItemEvent e )
{
• Class ItemEvent
– getStateChange
• Returns ItemEvent.SELECTED or
ItemEvent.DESELECTED
 2000 Prentice Hall, Inc. All rights reserved.
31
12.7 JCheckBox and JRadioButton
• JTextField
– Method setText( fontObject )
• new Font( name, style_CONSTANT, size )
• style_CONSTANT - FONT.PLAIN, BOLD, ITALIC
– Can add to get combinations
• Example
– Use JCheckBoxes to change the font of a JTextField
 2000 Prentice Hall, Inc. All rights reserved.
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 12.12: CheckBoxTest.java
// Creating Checkbox buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. import
public class CheckBoxTest extends JFrame {
private JTextField t;
private JCheckBox bold, italic;
1.1 Declarations
1.2 Initialize
JCheckBoxes
public CheckBoxTest()
{
super( "JCheckBox Test" );
1.3 Register event
handler
Container c = getContentPane();
c.setLayout(new FlowLayout());
t = new JTextField( "Watch the font style change", 20 );
t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) );
c.add( t );
// create checkbox objects
bold = new JCheckBox( "Bold" );
c.add( bold );
Create JCheckBoxes
italic = new JCheckBox( "Italic" );
c.add( italic );
CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener( handler );
 2000 Prentice Hall, Inc. All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
33
italic.addItemListener( handler );
Outline
addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
2. main
3. Inner class (event
handler)
setSize( 275, 100 );
show();
}
public static void main( String
{
new CheckBoxTest();
}
3.1 getStateChange
Because CheckBoxHandler implements
ItemListener, it must define method
args[] )
itemStateChanged
private class CheckBoxHandler implements ItemListener
{
getStateChange
returns
private int valBold = Font.PLAIN;
ItemEvent.SELECTED or
private int valItalic = Font.PLAIN;
ItemEvent.DESELECTED
public void itemStateChanged( ItemEvent e )
{
if ( e.getSource() == bold )
if ( e.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
 2000 Prentice Hall, Inc. All rights reserved.
34
62
63
64
65
66
67
68
69
70
71
72
73
74 }
Outline
if ( e.getSource() == italic )
if ( e.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
t.setFont(
new Font( "TimesRoman", valBold + valItalic, 14 ) );
t.repaint();
}
}
Use setFont to update the
JTextField.
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
35
12.7 JCheckBox and JRadioButton
• Radio buttons
– Have two states: selected and deselected
– Normally appear as a group
• Only one radio button in the group can be selected at time
• Selecting one button forces the other buttons off
– Mutually exclusive options
– ButtonGroup - maintains logical relationship between
radio buttons
• Class JRadioButton
– Constructor
• JRadioButton( "Label", selected )
• If selected true, JRadioButton initially selected
 2000 Prentice Hall, Inc. All rights reserved.
36
12.7 JCheckBox and JRadioButton
• Class JRadioButton
– Generates ItemEvents (like JCheckBox)
• Class ButtonGroup
– ButtonGroup myGroup = new ButtonGroup();
– Binds radio buttons into logical relationship
– Method add
• Associate a radio button with a group
myGroup.add( myRadioButton )
 2000 Prentice Hall, Inc. All rights reserved.
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 12.12: RadioButtonTest.java
// Creating radio buttons using ButtonGroup and JRadioButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonTest extends JFrame {
private JTextField t;
private Font plainFont, boldFont,
italicFont, boldItalicFont;
private JRadioButton plain, bold, italic, boldItalic;
private ButtonGroup radioGroup;
Outline
1. import
1.1 Declarations
1.2 Initialization
public RadioButtonTest()
{
super( "RadioButton Test" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
t = new JTextField( "Watch the font
c.add( t );
Initialize radio buttons. Only
styleone
change",
25 selected.
);
is initially
// Create radio buttons
plain = new JRadioButton( "Plain", true );
c.add( plain );
bold = new JRadioButton( "Bold", false);
c.add( bold );
italic = new JRadioButton( "Italic", false );
c.add( italic );
 2000 Prentice Hall, Inc. All rights reserved.
38
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
boldItalic = new JRadioButton( "Bold/Italic", false );
c.add( boldItalic );
Outline
// register events
RadioButtonHandler handler = new RadioButtonHandler();
2. Register event
plain.addItemListener( handler );
Create a ButtonGroup.
Only
handler
bold.addItemListener( handler );
one radio button in the group may
italic.addItemListener( handler );
be selected at a time. 2.1 ButtonGroup
boldItalic.addItemListener( handler );
// create logical relationship between JRadioButtons
2.2 add
radioGroup = new ButtonGroup();
Method add adds radio
radioGroup.add( plain );
buttons to the ButtonGroup
radioGroup.add( bold );
radioGroup.add( italic );
radioGroup.add( boldItalic );
plainFont = new Font( "TimesRoman", Font.PLAIN, 14 );
boldFont = new Font( "TimesRoman", Font.BOLD, 14 );
italicFont = new Font( "TimesRoman", Font.ITALIC, 14 );
boldItalicFont =
new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 );
t.setFont( plainFont );
setSize( 300, 100 );
show();
}
 2000 Prentice Hall, Inc. All rights reserved.
39
59
public static void main( String args[] )
60
{
61
RadioButtonTest app = new RadioButtonTest();
62
63
app.addWindowListener(
64
new WindowAdapter() {
65
public void windowClosing( WindowEvent e )
66
{
67
System.exit( 0 );
68
}
69
}
70
);
71
}
72
73
private class RadioButtonHandler implements ItemListener {
74
public void itemStateChanged( ItemEvent e )
75
{
76
if ( e.getSource() == plain )
77
t.setFont( plainFont );
78
else if ( e.getSource() == bold )
79
t.setFont( boldFont );
80
else if ( e.getSource() == italic )
81
t.setFont( italicFont );
82
else if ( e.getSource() == boldItalic )
83
t.setFont( boldItalicFont );
84
85
t.repaint();
86
}
87
}
88 }
 2000 Prentice Hall, Inc. All rights reserved.
Outline
3. main
4. Inner class (event
handler)
40
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
41
12.8 JComboBox
• Combo box (drop down list)
– List of items, user makes a selection
– Class JComboBox
• Generate ItemEvents
• JComboBox
– Constructor
JComboBox ( arrayOfNames )
– Numeric index keeps track of elements
• First element added at index 0
• First item added is appears as currently selected item when
combo box appears
 2000 Prentice Hall, Inc. All rights reserved.
42
12.8 JComboBox
• JComboBox methods
– getSelectedIndex
• Returns the index of the currently selected item
• myComboBox.getSelectedIndex()
– setMaximumRowCount( n )
• Set max number of elements to display when user clicks
combo box
• Scrollbar automatically provided
• setMaximumRowCount( 3 )
• Example
– Use JComboBox to set the Icon for a JLabel
 2000 Prentice Hall, Inc. All rights reserved.
43
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 29.13: ComboBoxTest.java
// Using a JComboBox to select an image to display.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxTest extends JFrame {
private JComboBox images;
private JLabel label;
private String names[] =
{ "bug1.gif", "bug2.gif",
"travelbug.gif", "buganim.gif" };
private Icon icons[] =
{ new ImageIcon( names[ 0 ] ),
new ImageIcon( names[ 1 ] ),
new ImageIcon( names[ 2 ] ),
new ImageIcon( names[ 3 ] ) };
public ComboBoxTest()
{
super( "Testing JComboBox" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
images = new JComboBox( names );
images.setMaximumRowCount( 3 );
images.addItemListener(
new ItemListener() {
 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. import
1.1 Initialization
1.2 Constructor
2. Initialize JComboBox
2.1
setMaximumRowCount
Initialize JComboBox with2.2 Register
an array of Strings.
ItemListener
(anonymous inner
class)
Set the number of rows to be
displayed at a time.
44
Outline
31
public void itemStateChanged( ItemEvent e )
32
{
33
label.setIcon(
34
icons[ images.getSelectedIndex() ] );
35
}
2.3
36
}
getSelectedIndex
37
);
38
Use method getSelectedIndex
39
c.add( images );
3. main
to determine which Icon to use.
40
41
label = new JLabel( icons[ 0 ] );
42
c.add( label );
43
44
setSize( 350, 100 );
45
show();
46
}
47
48
public static void main( String args[] )
49
{
50
ComboBoxTest app = new ComboBoxTest();
51
52
app.addWindowListener(
53
new WindowAdapter() {
54
public void windowClosing( WindowEvent e )
55
{
56
System.exit( 0 );
57
}
58
}
59
);
60
}
61 }
 2000 Prentice Hall, Inc. All rights reserved.
45
12.9 JList
• List
– Displays series of items, may select one or more
– This section, discuss single-selection lists
• Class JList
– Constructor JList( arrayOfNames )
• Takes array of Objects (Strings) to display in list
– setVisibleRowCount( n )
• Displays n items at a time
• Does not provide automatic scrolling
 2000 Prentice Hall, Inc. All rights reserved.
46
12.9 JList
• JScrollPane object used for scrolling
40
c.add( new JScrollPane( colorList ) );
– Takes component to which to add scrolling as argument
– Add JScrollPane object to content pane
• JList methods
– setSelectionMode( selection_CONSTANT )
– SINGLE_SELECTION
• One item selected at a time
– SINGLE_INTERVAL_SELECTION
• Multiple selection list, allows contiguous items to be selected
– MULTIPLE_INTERVAL_SELECTION
• Multiple-selection list, any items can be selected
 2000 Prentice Hall, Inc. All rights reserved.
47
12.9 JList
• JList methods
– getSelectedIndex()
• Returns index of selected item
• Event handlers
– Implement interface ListSelectionListener
(javax.swing.event)
– Define method valueChanged
– Register handler with addListSelectionListener
• Example
– Use a JList to select the background color
 2000 Prentice Hall, Inc. All rights reserved.
1 // Fig. 12.14: ListTest.java
2 // Selecting colors from a JList.
3 import java.awt.*;
4
5
6
7
8
9
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListTest extends JFrame {
private JList colorList;
10
11
12
13
14
15
16
private Container c;
17
18
19
20
21
22
23
24
25
26
27
28
29
private Color colors[] =
{ Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray,
Color.magenta, Color.orange, Color.pink, Color.red,
Color.white, Color.yellow };
private String colorNames[] =
{ "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green",
"Light Gray", "Magenta", "Orange", "Pink", "Red",
"White", "Yellow" };
public ListTest()
{
super( "List Test" );
c = getContentPane();
c.setLayout( new FlowLayout() );
 2000 Prentice Hall, Inc. All rights reserved.
48
Outline
1. import
1.1 Declarations
1.2 Initialize
colorNames and
colors
1.3 Constructor
49
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// create a list with the items in the colorNames array
colorList = new JList( colorNames );
colorList.setVisibleRowCount( 5 );
// do not allow multiple selections
colorList.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION );
// add a JScrollPane containing the JList
// to the content pane
c.add( new JScrollPane( colorList ) );
Outline
Initialize JList with array of
Strings, and show 5 items at
2. Create JList
a time.
2.1
setVisibleRowCount
Make the JList
a singleselection list.
2.2
setSelectionMode
Create a new JScrollPane
object, initialize it with a JList,
and attach it to the content
pane.
2.3 JScrollPane
// set up event handler
colorList.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged( ListSelectionEvent e )
{
c.setBackground(
colors[ colorList.getSelectedIndex() ] );
}
}
);
Change the color
3. Event handler
4. main
according to the item
selected (use getSelectedIndex).
setSize( 350, 150 );
show();
}
public static void main( String args[] )
{
ListTest app = new ListTest();
 2000 Prentice Hall, Inc. All rights reserved.
50
Outline
60
61
app.addWindowListener(
62
new WindowAdapter() {
63
public void windowClosing( WindowEvent e )
64
{
65
System.exit( 0 );
66
}
67
}
68
69
);
}
70 }
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
51
12.10 Multiple-Selection Lists
• Multiple selection lists
– SINGLE_INTERVAL_SELECTION
• Select a contiguous group of items by holding Shift key
– MULTIPLE_INTERVAL_SELECTION
• Select any amount of items
• Hold Ctrl key and click each item to select
• JList methods
– getSelectedValues()
• Returns an array of Objects representing selected items
– setListData( arrayOfObjects )
• Sets items of JList to elements in arrayOfObjects
 2000 Prentice Hall, Inc. All rights reserved.
52
12.10 Multiple-Selection Lists
• JList methods
– setFixedCellHeight( height )
• Specifies height in pixels of each item in JList
– setFixedCellWidth( width )
• As above, set width of list
• Example
– Have two multiple-selection lists
– Copy button copies selected items in first list to other list
 2000 Prentice Hall, Inc. All rights reserved.
53
1
// Fig. 12.15: MultipleSelection.java
2
// Copying items from one List to another.
3
import javax.swing.*;
4
import java.awt.*;
5
import java.awt.event.*;
Outline
1. import
6
7
public class MultipleSelection extends JFrame {
8
private JList colorList, copyList;
9
private JButton copy;
10
11
1.1 Initialize
colorNames
private String colorNames[] =
{ "Black", "Blue", "Cyan", "Dark Gray", "Gray",
12
"Green", "Light Gray", "Magenta", "Orange", "Pink",
13
"Red", "White", "Yellow" };
1.3
setVisibleRowCount
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public MultipleSelection()
{
super( "Multiple Selection Lists" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
Initialize the JList with an
array of Strings. 1.4
Specify thesetFixedCellHeight
number of items
to appear at a time.
1.5
Set the cell height
setSelectionMode
Specify that list is to be
MULTIPLE_INTERVAL_SELECTION
1.6 JScrollPane
colorList = new JList( colorNames );
colorList.setVisibleRowCount( 5 );
colorList.setFixedCellHeight( 15 );
colorList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
c.add( new JScrollPane( colorList ) );
 2000 Prentice Hall, Inc. All rights reserved.
1.2 Initialize JList
54
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Outline
// create copy button
copy = new JButton( "Copy >>>" );
copy.addActionListener(
new ActionListener() {
2. JButton
public void actionPerformed( ActionEvent e )
{
// place selected values in copyList
2.1 Event handler
copyList.setListData(
(anonymous inner
colorList.getSelectedValues() );
class)
}
}
Use the array returned by
);
2.2 setListData
getSelectedValues
to set
c.add( copy );
the items of copyList.
2.2.1
getSelectedValues
copyList = new JList( );
copyList.setVisibleRowCount( 5 );
copyList.setFixedCellWidth( 100 );
copyList.setFixedCellHeight( 15 );
copyList.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION );
c.add( new JScrollPane( copyList ) );
setSize( 300, 120 );
show();
}
 2000 Prentice Hall, Inc. All rights reserved.
2.3 Initialize JList
55
55
56
57
58
59
60
61
62
63
64
65
66
67
68 }
Outline
public static void main( String args[] )
{
MultipleSelection app = new MultipleSelection();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
3. main
}
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
56
12.11
Mouse Event Handling
• Mouse events
– Can be trapped for any GUI component derived from
java.awt.Component
– Mouse event handling methods
• Take a MouseEvent object
– Contains info about event, including x and y coordinates
– Methods getX and getY
– Interfaces MouseListener and
MouseMotionListener
• addMouseListener
• addMouseMotionListener
• Must define all methods
 2000 Prentice Hall, Inc. All rights reserved.
57
12.11
Mouse Event Handling
• Interface MouseListener
– public void mousePressed( MouseEvent e )
• Mouse pressed on a component
– public void mouseClicked( MouseEvent e )
• Mouse pressed and released
– public void mouseReleased( MouseEvent e )
• Mouse released
– public void mouseEntered( MouseEvent e )
• Mouse enters bounds of component
– public void mouseExited( MouseEvent e )
• Mouse leaves bounds of component
 2000 Prentice Hall, Inc. All rights reserved.
58
12.11
Mouse Event Handling
• Interface MouseMotionListener
– public void mouseDragged( MouseEvent e )
• Mouse pressed and moved
– public void mouseMoved( MouseEvent e )
• Mouse moved when over component
17
getContentPane().add( statusBar, BorderLayout.SOUTH );
– Adds component statusBar to the bottom portion of the
content pane
– More section 12.14.2
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 29.15: MouseTracker.java
// Demonstrating mouse events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
59
Outline
Class implements interfaces MouseListener and
MouseMotionListener to listen for mouse
events. There are seven methods to1.
define.
import
public class MouseTracker extends JFrame
implements MouseListener, MouseMotionListener {
private JLabel statusBar;
Puts the JLabel component
1. Class MouseTracker
(implements
at the bottom
MouseListener,
of the content pane. More later.
MouseMotion
Listener)
public MouseTracker()
{
super( "Demonstrating Mouse Events" );
statusBar = new JLabel();
getContentPane().add( statusBar, BorderLayout.SOUTH );
// application listens to its own mouse events
addMouseListener( this );
addMouseMotionListener( this );
setSize( 275, 100 );
show();
}
// MouseListener event handlers
public void mouseClicked( MouseEvent e )
{
 2000 Prentice Hall, Inc. All rights reserved.
1.2 Register event
handlers (this)
2. Define
event handler
Application is its own
event handler
methods
30
statusBar.setText( "Clicked at [" + e.getX() +
31
32
33
34
35
36
", " + e.getY() + "]" );
public void mousePressed( MouseEvent e )
{
statusBar.setText( "Pressed at [" + e.getX() +
", " + e.getY() + "]" );
}
public void mouseReleased( MouseEvent e )
{
statusBar.setText( "Released at [" + e.getX() +
43
", " + e.getY() + "]" );
44
45
46
47
48
49
50
51
52
53
}
54
55
56
57
58
59
}
60
Outline
}
37
38
39
40
41
42
60
public void mouseEntered( MouseEvent e )
{
statusBar.setText( "Mouse in window" );
}
public void mouseExited( MouseEvent e )
{
statusBar.setText( "Mouse outside window" );
// MouseMotionListener event handlers
public void mouseDragged( MouseEvent e )
{
statusBar.setText( "Dragged at [" + e.getX() +
", " + e.getY() + "]" );
 2000 Prentice Hall, Inc. All rights reserved.
getX and getY return
the coordinates
2.1 getX
and getY
of where the mouse event occurred.
61
62
63
64
65
}
61
Outline
public void mouseMoved( MouseEvent e )
{
statusBar.setText( "Moved at [" + e.getX() +
66
", " + e.getY() + "]" );
67
68
69
70
71
72
73
74
75
}
public static void main( String args[] )
{
MouseTracker app = new MouseTracker();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
76
77
78
79
80
81
82 }
{
System.exit( 0 );
}
}
);
}
 2000 Prentice Hall, Inc. All rights reserved.
3. main
62
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
63
12.12 Adapter Classes
• Time consuming to define all interface methods
– MouseListener and MouseMotionListener have
seven methods
• What if we only want to use one?
• Required to define all methods in interface
• Adapter class
– Implements an interface
• Default implementation (empty body) for all methods
– Programmer extends adapter class
• Overrides methods he wants to use
– Has "is a" relationship with interface
• MouseAdapter is a MouseListener
 2000 Prentice Hall, Inc. All rights reserved.
64
12.12 Adapter Classes
• Adapter classes
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
 2000 Prentice Hall, Inc. All rights reserved.
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener
65
12.12 Adapter Classes
18
19
20
21
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e )
{
– Anonymous inner class
• Extends MouseMotionAdapter (which implements
MouseMotionListener)
• Inner class gets default (empty body) implementation of
mouseMoved and mouseDragged
• Override methods want to use
 2000 Prentice Hall, Inc. All rights reserved.
66
12.12 Adapter Classes
40
Painter app = new Painter();
42
app.addWindowListener(
43
new WindowAdapter() {
44
public void windowClosing( WindowEvent e )
45
{
46
System.exit( 0 );
47
}
48
49
}
);
– Used in applications extending JFrame
– Interface WindowListener specifies seven methods
• WindowAdapter define these for us
– Only override the method we want
• windowClosing
• Enables use of close button
 2000 Prentice Hall, Inc. All rights reserved.
67
12.12 Adapter Classes
• Example program
– Simple paint program
– Draw oval whenever user drags mouse
– Only want to define method mouseDragged
• Use MouseMotionAdapter
 2000 Prentice Hall, Inc. All rights reserved.
1 // Fig. 12.19: Painter.java
2 // Using class MouseMotionAdapter.
3 import javax.swing.*;
68
Outline
4 import java.awt.event.*;
5 import java.awt.*;
1. import
6
7 public class Painter extends JFrame {
8
private int xValue = -10, yValue = -10;
1.1 addMouseMotion
9
Listener
10
public Painter()
11
{
1.2.
12
super( "A simple paint program" );
13
Use adapter class so we do not have MouseMotionAdapter
to define all the
14
getContentPane().add(
methods of interface MouseMotionListner.
15
new Label( "Drag the mouse to draw" ),
16
BorderLayout.SOUTH );
17
18
addMouseMotionListener(
19
new MouseMotionAdapter() {
20
public void mouseDragged( MouseEvent e )
21
{
22
xValue = e.getX();
23
yValue = e.getY();
Update xValue and yValue,
24
repaint();
then call repaint.
25
}
26
}
27
);
28
29
setSize( 300, 150 );
30
show();
31
}
 2000 Prentice Hall, Inc. All rights reserved.
69
Outline
32
33
public void paint( Graphics g )
34
{
35
36
g.fillOval( xValue, yValue, 4, 4 );
}
Draw an oval based at location
xValue, yValue. 2. paint
37
38
public static void main( String args[] )
39
{
40
Painter app = new Painter();
41
42
app.addWindowListener(
43
3.1
addWindowListener
new WindowAdapter() {
44
public void windowClosing( WindowEvent e )
45
{
46
System.exit( 0 );
47
}
48
}
49
50
3. main
);
}
51 }
 2000 Prentice Hall, Inc. All rights reserved.
3.2 WindowAdapter
70
12.12 Adapter Classes
• Class MouseEvent
– Inherits from InputEvent
– Can distinguish between buttons on multi-button mouse
• Combination of a mouse click and a keystroke
– Java assumes every mouse has a left mouse button
• Alt + click = center mouse button
• Meta + click = right mouse button
– Method getClickCount
• Returns number of mouse clicks (separate for each button)
– Methods isAltDown and isMetaDown
• Returns true if Alt or Meta key down when mouse clicked
 2000 Prentice Hall, Inc. All rights reserved.
71
12.12 Adapter Classes
• Class JFrame
– Method setTitle( "String" )
• Sets title bar of window
 2000 Prentice Hall, Inc. All rights reserved.
72
1 // Fig. 12.20: MouseDetails.java
2 // Demonstrating mouse clicks and
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// distinguishing between mouse buttons.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseDetails extends JFrame {
private String s = "";
private int xPos, yPos;
public MouseDetails()
{
super( "Mouse clicks and buttons" );
addMouseListener( new MouseClickHandler() );
setSize( 350, 150 );
show();
}
public void paint( Graphics g )
{
g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]",
xPos, yPos );
}
 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. import
1.1 Constructor
1.2 Register event
handler
2. paint
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
73
public static void main( String args[] )
{
MouseDetails app = new MouseDetails();
Outline
app.addWindowListener(
3. main
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
4. Inner class (event
System.exit( 0 ); Use a named inner class as the event handler.
Can still
handler)
}
inherit from MouseAdapter (extends MouseAdapter).
}
);
4.1 getClickCount
}
// inner class to handle mouse events
4.2 isMetaDown
private class MouseClickHandler extends MouseAdapter {
public void mouseClicked( MouseEvent e )
{
isAltDown
Use getClickCount,4.3
isAltDown,
xPos = e.getX();
and isMetaDown to determine the
yPos = e.getY();
String to use.
String s =
"Clicked " + e.getClickCount() + " time(s)";
if (
s
else
s
else
s
e.isMetaDown() )
// Right mouse button
+= " with right mouse button";
if ( e.isAltDown() ) // Middle mouse button
+= " with center mouse button";
// Left mouse button
+= " with left mouse button";
 2000 Prentice Hall, Inc. All rights reserved.
74
59
setTitle( s );
60
61
62
repaint();
// set the title bar of the window
Outline
}
}
Set the title bar.
63 }
4.4 setTitle
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
75
12.13 Keyboard Event Handling
• Interface KeyListener
– Handles key events (keys pressed on keyboard)
– Must define methods
• keyPressed - called when any key pressed
• keyTyped - called when non-action key pressed
– Action keys: arrow keys, home, end, page up, page down,
function keys, num lock, print screen, scroll lock, caps
lock, pause
• keyReleased - called for any key after it is released
• Each get a KeyEvent as an argument
– Subclass of InputEvent
 2000 Prentice Hall, Inc. All rights reserved.
76
12.13 Keyboard Event Handling
• KeyEvent methods
– getKeyCode
• Every key represented with a virtual key code (constant)
• Complete list in on-line documentation (java.awt.event)
– getKeyText
• Takes key code constant, returns name of key
– getKeyChar
• Gets Unicode character of key pressed
– isActionKey
• Returns true if key that generated event is an action key
 2000 Prentice Hall, Inc. All rights reserved.
77
12.13 Keyboard Event Handling
• KeyEvent methods
– getModifiers (from class InputEvent)
• Returns which modifiers were pressed
– getKeyModifierText ( e.getModifiers )
• Returns string containing names of modifier keys
• Upcoming example
– Create a JTextArea
– Modify text depending on what keys are pressed
 2000 Prentice Hall, Inc. All rights reserved.
78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
// Fig. 12.22: KeyDemo.java
// Demonstrating keystroke events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
1. import
public class KeyDemo extends JFrame implements KeyListener {
private String line1 = "", line2 = "";
private String line3 = "";
Class implements interface
private JTextArea textArea;
1.1 Class KeyDemo
(implements
KeyListener)
KeyListener,
so it
must define the three required methods.
public KeyDemo()
{
super( "Demonstrating Keystroke Events" );
1.2 addKeyListener
textArea = new JTextArea( 10, 15 );
textArea.setText( "Press any key on the keyboard..." );
textArea.setEnabled( false );
// allow frame to process Key events
addKeyListener( this );
getContentPane().add( textArea );
setSize( 350, 100 );
show();
}
 2000 Prentice Hall, Inc. All rights reserved.
Register the event handler.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public void keyPressed( KeyEvent e )
{
line1 = "Key pressed: " +
e.getKeyText( e.getKeyCode() );
setLines2and3( e );
}
getKeyCode
79
Outline
returns the virtual key
code. handling
2. Event
getKeyText converts the key code
to a
methods
KeyEvent e )
String containing the name.
public void keyReleased(
{
line1 = "Key released: " +
e.getKeyText( e.getKeyCode() );
setLines2and3( e );
}
public void keyTyped( KeyEvent e )
{
line1 = "Key typed: " + e.getKeyChar();
setLines2and3( e );
}
private void setLines2and3( KeyEvent e )
{
line2 = "This key is " +
( e.isActionKey() ? "" : "not " ) +
"an action key";
String temp =
e.getKeyModifiersText( e.getModifiers() );
line3 = "Modifier keys pressed: " +
( temp.equals( "" ) ? "none" : temp );
 2000 Prentice Hall, Inc. All rights reserved.
2.1 getKeyText
2.2 getKeyCode
2.3 isActionKey
2.4 Determine modifier
keys
Test if the key is
an action key
getModifiers returns the
modifier keys, and
getKeyModifersText
turns them into a String.
80
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 }
Outline
textArea.setText(
line1 + "\n" + line2 + "\n" + line3 + "\n" );
}
public static void main( String args[] )
{
KeyDemo app = new KeyDemo();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
 2000 Prentice Hall, Inc. All rights reserved.
3. main
81
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
82
12.14
Layout Managers
• Layout managers
– Arrange GUI components on a container
– Provide basic layout capabilities
• Easier to use than determining exact size and position of every
component
• Programmer concentrates on "look and feel" rather than details
 2000 Prentice Hall, Inc. All rights reserved.
83
12.14.1
FlowLayout
• Most basic layout manager
– Components placed left to right in order added
– When edge of container reached, continues on next line
– Components can be left-aligned, centered (default), or rightaligned
• FlowLayout methods
– setAlignment( position_CONSTANT )
• FlowLayout.LEFT, FlowLayout.CENTER,
FlowLayout.RIGHT
– layoutContainer( container )
• Update Container specified with layout
– I.e., content pane
 2000 Prentice Hall, Inc. All rights reserved.
84
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 29.17: FlowLayoutDemo.java
// Demonstrating FlowLayout alignments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. import
public class FlowLayoutDemo extends JFrame {
private JButton left, center, right;
private Container c;
private FlowLayout layout;
public FlowLayoutDemo()
{
super( "FlowLayout Demo" );
layout = new FlowLayout();
c = getContentPane();
c.setLayout( layout );
1.1 Declarations
1.2 Initialize
FlowLayout
setAlignment changes the
1.3 Create button
alignment of the layout.
1.4 Event handler
Use method layoutContainer to
update changes
1.4.1 setAlignment
left = new JButton( "Left" );
left.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
layout.setAlignment( FlowLayout.LEFT );
// re-align attached components
layout.layoutContainer( c );
}
 2000 Prentice Hall, Inc. All rights reserved.
1.4.2
layoutContainer
85
31
32
33
34
35
36
37
38
}
);
c.add( left );
center = new JButton( "Center" );
center.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
39
40
41
42
43
44
45
46
47
48
49
50
51
52
1.5 add JButton
2. JButton
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( c );
}
2.1 Event handler
3. JButton
}
);
c.add( center );
right = new JButton( "Right" );
right.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
53
54
55
56
57
58
59
60
Outline
{
layout.setAlignment( FlowLayout.RIGHT );
// re-align attached components
layout.layoutContainer( c );
}
}
);
 2000 Prentice Hall, Inc. All rights reserved.
3.1 Event handler
86
61
62
63
64
65
66
67
68
69
setSize( 300, 75 );
show();
}
4. main
public static void main( String args[] )
{
FlowLayoutDemo app = new FlowLayoutDemo();
70
71
72
73
74
75
76
77
78
79
80 }
Outline
c.add( right );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
87
12.14.2
BorderLayout
• BorderLayout
– Default manager for content pane
– Arrange components into 5 regions
• North, south, east, west, center
– Up to 5 components can be added directly
• One for each region
– Components placed in
• North/South - Region is as tall as component
• East/West - Region is as wide as component
• Center - Region expands to take all remaining space
 2000 Prentice Hall, Inc. All rights reserved.
88
12.14.2
BorderLayout
• Methods
– Constructor: BorderLayout( hGap, vGap );
• hGap - horizontal gap space between regions
• vGap - vertical gap space between regions
• Default is 0 for both
– Adding components
• myContainer.add( component, position )
• component - component to add
• position - BorderLayout.NORTH
– SOUTH, EAST, WEST, CENTER similar
 2000 Prentice Hall, Inc. All rights reserved.
89
12.14.2
BorderLayout
• Methods
– setVisible( boolean ) ( in class JButton)
• If false, hides component
– layoutContainer( container ) - updates
container, as before
 2000 Prentice Hall, Inc. All rights reserved.
90
1
2
3
4
5
6
7
8
Outline
// Fig. 29.18: BorderLayoutDemo.java
// Demonstrating BorderLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
1. import
public class BorderLayoutDemo extends JFrame
implements ActionListener {
1.1 Declarations
9
10
11
private JButton b[];
private String names[] =
{ "Hide North", "Hide South", "Hide East",
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"Hide West", "Hide Center" };
private BorderLayout layout;
28
29
30
public BorderLayoutDemo()
{
super( "BorderLayout Demo" );
1.3 Create JButtons
Set horizontal and vertical
spacing in constructor.
1.4 Register event
handler
layout = new BorderLayout( 5, 5 );
Container c = getContentPane();
c.setLayout( layout );
// instantiate button objects
b = new JButton[ names.length ];
for ( int i = 0; i < names.length; i++ ) {
b[ i ] = new JButton( names[ i ] );
b[ i ].addActionListener( this );
}
 2000 Prentice Hall, Inc. All rights reserved.
1.2 Initialize layout
91
Outline
31
32
33
// order not important
c.add( b[ 0 ], BorderLayout.NORTH );
// North position
34
c.add( b[ 1 ], BorderLayout.SOUTH );
// South position
35
c.add( b[ 2 ], BorderLayout.EAST );
// East position
36
c.add( b[ 3 ], BorderLayout.WEST );
// West position
37
c.add( b[ 4 ], BorderLayout.CENTER ); // Center position
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2. add (specify
position)
3. actionPerformed
setSize( 300, 200 );
show();
}
public void actionPerformed( ActionEvent e )
{
for ( int i = 0; i < b.length; i++ )
if ( e.getSource() == b[ i ] )
b[ i ].setVisible( false );
else
b[ i ].setVisible( true );
// re-layout the content pane
layout.layoutContainer( getContentPane() );
}
public static void main( String args[] )
{
BorderLayoutDemo app = new BorderLayoutDemo();
58
59
app.addWindowListener(
60
new Inc.
WindowAdapter()
 2000 Prentice Hall,
All rights reserved. {
3.1 setVisible
Hide the button 3.2
that layoutContainer
generated the event.
4. main
Recalculates layout of content
pane.
92
61
public void windowClosing( WindowEvent e )
62
{
63
System.exit( 0 );
64
}
65
}
66
67
Outline
);
}
68 }
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
93
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
94
29.11.3
GridLayout
• GridLayout
– Divides container into a grid
– Components placed in rows and columns
– All components have same width and height
• Added starting from top left, then from left to right
• When row full, continues on next row, left to right
• Constructors
– GridLayout( rows, columns, hGap, vGap )
• Specify number of rows and columns, and horizontal and
vertical gaps between elements (in pixels)
– GridLayout( rows, columns )
• Default 0 for hGap and vGap
 2000 Prentice Hall, Inc. All rights reserved.
95
29.11.3
GridLayout
• Updating containers
– Container method validate
• Re-layouts a container for which the layout has changed
– Example:
Container c = getContentPane;
c.setLayout( myLayout );
if ( x = 3 ){
c.setLayout( myLayout2 );
c.validate();
}
• Changes layout and updates c if condition met
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
96
// Fig. 29.19: GridLayoutDemo.java
// Demonstrating GridLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
1. import
public class GridLayoutDemo extends JFrame
implements ActionListener {
9
10
11
private JButton b[];
private String names[] =
{ "one", "two", "three", "four", "five", "six" };
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private boolean toggle = true;
private Container c;
private GridLayout grid1, grid2;
public GridLayoutDemo()
{
super( "GridLayout Demo" );
grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );
c = getContentPane();
c.setLayout( grid1 );
// create and add buttons
b = new JButton[ names.length ];
for (int i = 0; i < names.length; i++ ) {
b[ i ] = new JButton( names[ i ] );
b[ i ].addActionListener( this );
 2000 Prentice Hall, Inc. All rights reserved.
1.1 Declarations
1.2 Initialize layout
1.3 Register event
Create two GridLayouts,
handler
a 2 by 3 and a 3 by 2 (rows,
columns).
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
97
c.add( b[ i ] );
}
setSize( 300, 150 );
show();
Add buttons to layout.
Added from left to right in
order.
}
public void actionPerformed( ActionEvent e )
{
if ( toggle )
Toggle layouts and
c.setLayout( grid2 );
update content pane
else
with validate.
c.setLayout( grid1 );
toggle = !toggle;
c.validate();
}
public static void main( String args[] )
{
GridLayoutDemo app = new GridLayoutDemo();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
57
{
58
System.exit( 0 );
59
}
60
}
61
);
62
}
63 }
 2000 Prentice Hall, Inc. All rights reserved.
Outline
1.4 add
2. actionPerformed
3. main
98
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
99
29.12
Panels
• Complex GUIs
– Each component needs to be placed in an exact location
– Can use multiple panels
• Each panel's components arranged in a specific layout
• Panels
– Class JPanel inherits from JComponent, which inherits
from java.awt.Container
• Every JPanel is a Container
– JPanels can have components (and other JPanels)
added to them
• JPanel sized to components it contains
• Grows to accomodate components as they are added
 2000 Prentice Hall, Inc. All rights reserved.
100
29.12 Panels
• Usage
– Create panels, and set the layout for each
– Add components to the panels as needed
– Add the panels to the content pane (default
BorderLayout)
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 12.27: PanelDemo.java
// Using a JPanel to help lay out components.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelDemo extends JFrame {
private JPanel buttonPanel;
private JButton buttons[];
public PanelDemo()
{
super( "Panel Demo" );
Container c = getContentPane();
buttonPanel = new JPanel();
buttons = new JButton[ 5 ];
101
Outline
1. import
1.1 Declarations
1.2 Initialize
buttonPanel
1.3 GridLayout
Create a new panel.
1.4 ButtonPanel.add
buttonPanel.setLayout(
new GridLayout( 1, buttons.length ) );
1.5 c.add
for ( int i = 0; i < buttons.length; i++ ) {
buttons[ i ] = new JButton( "Button " + (i + 1) );
buttonPanel.add( buttons[ i ] );
Add components
}
to panel.
c.add( buttonPanel, BorderLayout.SOUTH );
setSize( 425, 150 );
show();
}
 2000 Prentice Hall, Inc. All rights reserved.
Add panel to the content pane
(BorderLayout.SOUTH).
102
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 }
Outline
public static void main( String args[] )
{
PanelDemo app = new PanelDemo();
2. main
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
Program Output
JPanel sized to its
components. Grows as
needed.
 2000 Prentice Hall, Inc. All rights reserved.