Transcript Document

Chapter 13 - Graphical User Interface
Components: Part 1
Outline
13.1
13.2
13.3
13.4
13.5
13.6
13.7
13.8
13.9
13.10
13.11
13.12
13.13
13.14
Introduction
Overview of Swing Components
JLabel
Event Handling
TextFields
How Event Handling Works
JButton
JCheckBox and JRadioButton
JComboBox
JList
Multiple-Selection Lists
Mouse Event Handling
Adapter Classes
Key Event Handling
Chapter 13 - Graphical User Interface
Components: Part 1
Outline
13.15
13.16
13.17
Layout Managers
13.15.1 FlowLayout
13.15.2 BorderLayout
13.15.3 GridLayout
Panels
(Optional Case Study) Thinking About Objects: Use Cases
Olay İşleme
• Olay:
– Kaynaktaki bir durum değişikliğini tarif eden nesnedir.
– Butona basmak,klavye ile karakter girme,fareyi tıklama...
• Olay Kaynakları
– Olay üreten nesne
• Olay Dinleyicileri
– Olay olduğunda haber verilen nesnedir.
– Java.awt.event  olayları alan ve işleyen metotların
bulunduğu paket.
java.awt.event Paketindeki Ana Olay Sınıfları
Olay Sınıfı
Açıklama
AdjustmentEvent
Kaydırma çubuğu yönlendirildiğinde üretilir.
ComponentEvent
Bir bileşen gizlendiğinde, taşındığında, boyutu değiştirildiğinde yada görünür hale geldiğinde üretilir.
ContainerEvent
Bir bileşen, bir konteynere eklenince yada ondan çıkarılınca üretilir.
FocusEvent
Bir bileşen kalvye odağı kazandığında yada kaybettiğinde üretilir.
InputEvent
Bileşen girdi olay sısnfları için bir üst sınıfı soyutlar
ItemEvent
Onay kutusu yada liste öğesi tıklandığında yada bir seçim işi onaylandığında yada bir menü
seçildiğinde üretilir.
KeyEvent
Klavyeden bir girdi alındığında üretilir.
MouseEvent
Fare sürüklendiğinde,taşındığında,tıklandığında,basıldığında, yada bırakıldığında üretilir
TextEvent
Bir metin alanının yada sahasının değeri değiştiğinde üretilir.
WindowEvent
Bir pencere, etkinleştiğinde, kapandığında, etkinsizleştiğinde, simgeleştirildiğinde... Üretilir.
ActionEvent
Bir düğmeye basıldığında, bir liste öğesi iki kere tıklandığında, yada bir menü öğesi seçildiğinde
Olay Kaynakları
•
•
•
•
•
•
•
•
Button
CheckBox
Choice
List
Menu Item
Scrollbar
Metin
Window
Olay Dinleyicileri Arabirimleri
• ActionListener
– void actionPerformed(ActionEvent e)
• AdjustmentListener
– void adjustmentValueChanged(AdjustmentEvent e)
• ComponentListener
– void componentResized(ComponentEvent e)
– void componentMoved(ComponentEvent e)
– void componentShown(ComponentEvent e)
– void componentHidden(ComponentEvent e)
• ContainerListener
– void componentAdded(ContainerEvent e)
– void componentRemoved(ContainerEvent e)
Olay Dinleyicileri Arabirimleri
• FocusListener
– void focusGained(FocusEvent e)
– void focusLost(FocusEvent e)
• ItemListener
– void itemStateChanged(ItemEvent e)
• KeyListener
– void keyPressed(KeyEvent e)
– void keyReleased(KeyEvent e)
– void keyTyped(KeyEvent e)
• MouseListener
– void mouseClicked(MouseEvent e)
– void mouseEntered(MouseEvent e)
– void mouseExited(MouseEvent e)
– void mousePressed(MouseEvent e)
– void mouseReleased(MouseEvent e)
Olay Dinleyicileri Arabirimleri
• MouseMotionListener
– void mouseDragged(MouseEvent e)
– void mouseMoved(MouseEvent e)
• TextListener
– void textChanged(TextEvent e)
• WindowListener
– void windowActivated(WindowEvent e)
– void windowClosed(WindowEvent e)
– void windowDeactivated(WindowEvent e)
– void windowDeiconified(WindowEvent e)
– void windowIconified(WindowEvent e)
– void windowOpened(WindowEvent e)
Fig. 13.2 Some basic GUI components
Component
JLabel
Description
JTextField
An area in which the user inputs data from the keyboard. The area can also
display information.
JButton
An area that triggers an event when clicked with the mouse.
JCheckBox
A GUI component that is either selected or not selected.
JComboBox
A drop-down list of items from which the user can make a selection by
clicking an item in the list or possibly by typing into the box.
JList
An area containing a list of items from which the user can make a selection
by clicking on any element in the list. Multiple elements can be selected.
JPanel
A container in which components can be placed and organized.
An area where uneditable text or icons can be displayed.
13.2 Overview of Swing Components
• Swing GUI components
– Package javax.swing
– Components originate from AWT (package java.awt)
– Contain look and feel
• Appearance and how users interact with program
– Lightweight components
• Written completely in Java
13.2 Overview of Swing Components
• Class Component
– Contains method paint for drawing Component onscreen
• Class Container
– Collection of related components
– Contains method add for adding components
• Class JComponent
– Pluggable look and feel for customizing look and feel
– Shortcut keys (mnemonics)
– Common event-handling capabilities
Fig. 13.3 Common superclasses of many of the
Swing components
Object
Object
Component
Component
Container
Container
JComponent
JComponent
13.3 JLabel
• Label
– Provide text on GUI
– Defined with class JLabel
– Can display:
• Single line of read-only text
• Image
• Text and image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 13.4: LabelTest.java
// Demonstrating the JLabel class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
LabelTest.java
Line 8
Declare three JLabels
Line 20
// set up GUI
public LabelTest()
{
super( "Testing JLabel" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
container.add( label1 );
Line 21
Create first JLabel with
text “Label with text”
Tool tip is text that appears when
user moves cursor over JLabel
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// JLabel constructor with string, Icon and alignment arguments
Icon bug = new ImageIcon( "bug1.gif" );
label2 = new JLabel( "Label with text and icon", bug,
Create second JLabel
SwingConstants.LEFT );
with text to left ofLabelTest.java
image
label2.setToolTipText( "This is label2" );
container.add( label2 );
Lines 16-17
// JLabel constructor no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
label3.setHorizontalTextPosition( SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
container.add( label3 );
setSize( 275, 170 );
setVisible( true );
} // end constructor
public static void main( String args[] )
{
LabelTest application = new LabelTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Lines 32-37
Create third JLabel
with text below image
50
51
} // end class LabelTest
LabelTest.java
13.4 Event Handling
• GUIs are event driven
– Generate events when user interacts with GUI
• e.g., moving mouse, pressing button, typing in text field, etc.
• Class java.awt.AWTEvent
Fig. 13.5
Some event classes of package
java.awt.event
Object
Object
ActionEvent
ActionEvent
EventObject
EventObject
AdjustmentEvent
AdjustmentEvent
AWTEvent
AWTEvent
ContainerEvent
ContainerEvent
ItemEvent
ItemEvent
FocusEvent
FocusEvent
TextEvent
TextEvent
PaintEvent
PaintEvent
ComponentEvent
ComponentEvent
WindowEvent
WindowEvent
InputEvent
InputEvent
KeyEvent
KeyEvent
MouseEvent
MouseEvent
MouseWheelEvent
MouseWheelEvent
13.4 Event Handling
• Event-handling model
– Three parts
• Event source
– GUI component with which user interacts
• Event object
– Encapsulates information about event that occurred
• Event listener
– Receives event object when notified, then responds
– Programmer must perform two tasks
• Register event listener for event source
• Implement event-handling method (event handler)
Fig. 13.6 Event-listener interfaces of package
java.awt.event
interface
«interface»
ActionListener
ActionListener
interface
«interface»
AdjustmentListener
AdjustmentListener
interface
«interface»
ComponentListener
ComponentListener
interface
«interface»
ContainerListener
ContainerListener
interface
«interface»
FocusListener
FocusListener
interface
«interface»
EventListener
EventListener
interface
«interface»
ItemListener
ItemListener
interface
«interface»
KeyListener
KeyListener
interface
«interface»
MouseListener
MouseListener
interface
«interface»
MouseMotionListener
MouseMotionListener
interface
«interface»
TextListener
TextListener
interface
«interface»
WindowListener
TextListener
13.5 TextFields
• JTextField
– Single-line area in which user can enter text
• JPasswordField
– Extends JTextField
– Hides characters that user enters
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
// Fig. 13.7: TextFieldTest.java
// Demonstrating the JTextField class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldTest extends JFrame {
private JTextField textField1, textField2, textField3;
private JPasswordField passwordField;
// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
TextFieldTest.j
ava
Declare
three8-9
Lines
JTextFields and one
JPasswordField
Line 20
Line 24
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// construct textfield with default sizing
textField1 = new JTextField( 10 );
container.add( textField1 );
// construct textfield with default text
textField2 = new JTextField( "Enter text here" );
container.add( textField2 );
First JTextField
contains empty string
Second JTextField contains
text “Enter text here”
27
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
// construct textfield with default text,
// 20 visible elements and no event handler
textField3 = new JTextField( "Uneditable text field", 20 );
textField3.setEditable( false );
container.add( textField3 );
// construct passwordfield with default text
passwordField = new JPasswordField( "Hidden text" );
container.add( passwordField );
// register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
textField3.addActionListener( handler );
passwordField.addActionListener( handler );
setSize( 325, 100 );
setVisible( true );
Third JTextField
TextFieldTest.j
contains uneditable
text
ava
JPasswordField contains
text “Hidden Line
text,”
30 but text
appears as series of asterisks (*)
Line 34
Lines 39-42
Register GUI components with
TextFieldHandler
(register for ActionEvents)
} // end constructor TextFieldTest
public static void main( String args[] )
{
TextFieldTest application = new TextFieldTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// private inner class for event handling
private class TextFieldHandler implements ActionListener {
// process textfield events
public void actionPerformed( ActionEvent event )
{
String string = "";
// user pressed Enter in JTextField textField1
if ( event.getSource() == textField1 )
string = "textField1: " + event.getActionCommand();
// user pressed Enter in JTextField textField2
else if ( event.getSource() == textField2 )
string = "textField2: " + event.getActionCommand();
// user pressed Enter in JTextField textField3
else if ( event.getSource() == textField3 )
string = "textField3: " + event.getActionCommand();
// user pressed Enter in JTextField passwordField
else if ( event.getSource() == passwordField ) {
string = "passwordField: " +
new String( passwordField.getPassword() );
}
TextFieldTest.j
Every TextFieldHandler
instance is an ActionListener
ava
Line 56
Method actionPerformed
invoked when user
Linepresses
59
Enter in GUI field
80
81
82
83
84
85
86
87
JOptionPane.showMessageDialog( null, string );
} // end method actionPerformed
} // end private inner class TextFieldHandler
} // end class TextFieldTest
TextFieldTest.j
ava
TextFieldTest.j
ava
13.6 How Event Handling Works
• Two open questions from Section 13.4
– How did event handler get registered?
• Answer:
– Through component’s method addActionListener
– Lines 39-42 of TextFieldTest.java
– How does component know to call actionPerformed?
• Answer:
– Event is dispatched only to listeners of appropriate type
– Each event type has corresponding event-listener interface
• Event ID specifies event type that occurred
Fig. 13.8 Event registration for JTextField
textField1
textField1
handler
listenerList
JTextField
object
public void actionPerformed(
ActionEvent event )
{
// event handled here
}
TextFieldHandler
object
...
This reference is created by the statement
textField1.addActionListener( handler );
13.7 JButton
• Button
– Component user clicks to trigger a specific action
– Several different types
•
•
•
•
Command buttons
Check boxes
Toggle buttons
Radio buttons
– javax.swing.AbstractButton subclasses
• Command buttons are created with class JButton
– Generate ActionEvents when user clicks button
Fig. 13.9 Swing button hierarchy
JComponent
JComponent
AbstractButton
AbstractButton
JButton
JToggleButton
JButton
JToggleButton
JCheckBox
JCheckBox
JRadioButton
JRadioButton
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
// Fig. 13.10: ButtonTest.java
// Creating JButtons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest extends JFrame {
private JButton plainButton, fancyButton;
ButtonTest.java
Create two references
to JButton instances
// set up GUI
public ButtonTest()
{
super( "Testing Buttons" );
Line 8
Line 20
Lines 24-26
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );
Icon bug1 = new ImageIcon( "bug1.gif" );
Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
container.add( fancyButton );
Instantiate JButton with text
Instantiate JButton with
image and rollover image
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
// create an instance of inner class ButtonHandler
// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
plainButton.addActionListener( handler );
Instantiate ButtonHandler
for JButton event handling
ButtonTest.java
Register JButtons to receive
events from ButtonHandler
Line 31
setSize( 275, 100 );
setVisible( true );
Lines 32-33
} // end ButtonTest constructor
Line 50
public static void main( String args[] )
{
ButtonTest application = new ButtonTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// inner class for button event handling
private class ButtonHandler implements ActionListener {
// handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( ButtonTest.this,
"You pressed: " + event.getActionCommand() );
}
When user clicks JButton,
ButtonHandler invokes
method actionPerformed
of all registered listeners
55
56
57
58
} // end private inner class ButtonHandler
} // end class ButtonTest
ButtonTest.java
13.8 JCheckBox and JRadioButton
• State buttons
– On/Off or true/false values
– Java provides three types
• JToggleButton
• JCheckBox
• JRadioButton
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 13.11: CheckBoxTest.java
// Creating JCheckBox buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckBoxTest extends JFrame {
private JTextField field;
private JCheckBox bold, italic;
// set up GUI
public CheckBoxTest()
{
super( "JCheckBox Test" );
CheckBoxTest.ja
va
Line 9
Declare two JCheckBox instances
Line 22
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField and set its font
field = new JTextField( "Watch the font style change", 20 );
field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
container.add( field );
Set JTextField font
to Serif, 14-point plain
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// create checkbox objects
bold = new JCheckBox( "Bold" );
container.add( bold );
italic = new JCheckBox( "Italic" );
container.add( italic );
Instantiate JCheckBoxs for bolding and
CheckBoxTest.ja
italicizing JTextField text,
respectively
va
// register listeners for JCheckBoxes
CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener( handler );
italic.addItemListener( handler );
Lines 26 and 29
Register JCheckBoxs to receive
Lines 34-35
events from CheckBoxHandler
setSize( 275, 100 );
setVisible( true );
} // end CheckBoxText constructor
public static void main( String args[] )
{
CheckBoxTest application = new CheckBoxTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// private inner class for ItemListener event handling
private class CheckBoxHandler implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
When user selects JCheckBox,
CheckBoxTest.ja
CheckBoxHandler
vainvokes
method itemStateChanges of
all registered listeners
Line 54
// respond to checkbox events
public void itemStateChanged( ItemEvent event )
{
// process bold checkbox events
if ( event.getSource() == bold )
valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN;
// process italic checkbox events
if ( event.getSource() == italic )
Change JTextField
valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN;
Line 65
font, depending
on which JCheckBox was selected
// set text field font
field.setFont( new Font( "Serif", valBold + valItalic, 14 ) );
} // end method itemStateChanged
} // end private inner class CheckBoxHandler
} // end class CheckBoxTest
CheckBoxTest.ja
va
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
// Fig. 13.12: RadioButtonTest.java
// Creating radio buttons using ButtonGroup and JRadioButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
RadioButtonTest
.java
Declare four JRadioButton instances
Lines 10-11
public class RadioButtonTest extends JFrame {
private JTextField field;
private Font plainFont, boldFont, italicFont, boldItalicFont;
private JRadioButton plainButton, boldButton, italicButton,
boldItalicButton;
private ButtonGroup radioGroup;
// create GUI and fonts
public RadioButtonTest()
{
super( "RadioButton Test" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField
field = new JTextField( "Watch the font style change", 25 );
container.add( field );
Line 12
JRadioButtons normally
appear as a ButtonGroup
27
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
// create radio buttons
plainButton = new JRadioButton( "Plain", true );
container.add( plainButton );
RadioButtonTest
.java
boldButton = new JRadioButton( "Bold", false );
container.add( boldButton );
italicButton = new JRadioButton( "Italic", false );
container.add( italicButton );
Instantiate JRadioButtons
for
Lines 28-35
manipulating JTextField text font
Lines 41-45
boldItalicButton = new JRadioButton( "Bold/Italic", false );
container.add( boldItalicButton );
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add( plainButton );
radioGroup.add( boldButton );
radioGroup.add( italicButton );
radioGroup.add( boldItalicButton );
JRadioButtons belong
to ButtonGroup
// create font objects
plainFont = new Font( "Serif", Font.PLAIN, 14 );
boldFont = new Font( "Serif", Font.BOLD, 14 );
italicFont = new Font( "Serif", Font.ITALIC, 14 );
boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
field.setFont( plainFont ); // set initial font
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// register events for JRadioButtons
plainButton.addItemListener( new RadioButtonHandler( plainFont ) );
Register JRadioButtons
boldButton.addItemListener( new RadioButtonHandler( boldFont ) );
italicButton.addItemListener(
to receive
events from
RadioButtonTest
new RadioButtonHandler( italicFont ) );
RadioButtonHandler
.java
boldItalicButton.addItemListener(
new RadioButtonHandler( boldItalicFont ) );
Lines 55-60
setSize( 300, 100 );
setVisible( true );
} // end RadioButtonTest constructor
public static void main( String args[] )
{
RadioButtonTest application = new RadioButtonTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// private inner class to handle radio button events
private class RadioButtonHandler implements ItemListener {
private Font font;
public RadioButtonHandler( Font f )
{
font = f;
}
81
82
83
84
85
86
87
88
89
90
// handle radio button events
public void itemStateChanged( ItemEvent event )
{
field.setFont( font );
}
} // end private inner class RadioButtonHandler
} // end class RadioButtonTest
When user selects JRadioButton,
RadioButtonHandler invokes
RadioButtonTest
method itemStateChanged of
.java
all registered listeners
Line 83
Set font corresponding to
JRadioButton Line
selected
85
13.9 JComboBox
• JComboBox
– List of items from which user can select
– Also called a drop-down list
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
// Fig. 13.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 imagesComboBox;
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 ] ) };
// set up GUI
public ComboBoxTest()
{
super( "Testing JComboBox" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
ComboBoxTest.ja
va
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// set up JComboBox and register its event handler
imagesComboBox = new JComboBox( names );
imagesComboBox.setMaximumRowCount( 3 );
imagesComboBox.addItemListener(
new ItemListener() {
// anonymous inner class
Instantiate JComboBox to
show three Strings from
ComboBoxTest.ja
names array
at a time
va
Register JComboBox to receive events
Lines 27-28
// handle JComboBox event
from
anonymous
ItemListener
public void itemStateChanged( ItemEvent event )
{
Line 29
// determine whether check box selected
if ( event.getStateChange() == ItemEvent.SELECTED )
Line 34
label.setIcon( icons[
imagesComboBox.getSelectedIndex() ] );
}
Lines 38-39
When user selects item in JComboBox,
}
// end anonymous inner class
ItemListener invokes method
itemStateChanged of all registered listeners
); // end call to addItemListener
container.add( imagesComboBox );
// set up JLabel to display ImageIcons
label = new JLabel( icons[ 0 ] );
container.add( label );
Set appropriate Icon
depending on user selection
52
53
54
55
56
57
58
59
60
61
62
63
setSize( 350, 100 );
setVisible( true );
} // end ComboBoxTest constructor
public static void main( String args[] )
{
ComboBoxTest application = new ComboBoxTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class ComboBoxTest
ComboBoxTest.ja
va
13.10 JList
• List
–
–
–
–
Series of items
user can select one or more items
Single-selection vs. multiple-selection
JList
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
// Fig. 13.14: ListTest.java
// Selecting colors from a JList.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListTest extends JFrame {
private JList colorList;
private Container container;
private final String colorNames[] = { "Black", "Blue", "Cyan",
"Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
"Orange", "Pink", "Red", "White", "Yellow" };
private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN,
Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY,
Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE,
Color.YELLOW };
// set up GUI
public ListTest()
{
super( "List Test" );
// get content pane and set its layout
container = getContentPane();
container.setLayout( new FlowLayout() );
ListTest.java
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
// create a list with items in colorNames array
colorList = new JList( colorNames );
colorList.setVisibleRowCount( 5 );
Use colorNames array
to populate JList
ListTest.java
// do not allow multiple selections
colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
// add a JScrollPane containing JList to content pane
container.add( new JScrollPane( colorList ) );
colorList.addListSelectionListener(
new ListSelectionListener() {
// anonymous
Line 34
JList allows single selections
Line 38
inner class
Register JList to receive events from
Line 43
anonymous ListSelectionListener
// handle list selection events
public void valueChanged( ListSelectionEvent event )
{
container.setBackground(
colors[ colorList.getSelectedIndex() ] );
}
} // end anonymous inner class
); // end call to addListSelectionListener
Line 30
Lines 45-46
When user selects item in JList,
ListSelectionListener
invokes method valueChanged of
all registered listeners
Set appropriate background
depending on user selection
53
54
55
56
57
58
59
60
61
62
63
64
setSize( 350, 150 );
setVisible( true );
} // end ListTest constructor
public static void main( String args[] )
{
ListTest application = new ListTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class ListTest
ListTest.java
13.11 Multiple-Selection Lists
• Multiple-selection list
– Select many items from Jlist
– Allows continuous range selection
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
// Fig. 13.15: MultipleSelectionTest.java
// Copying items from one List to another.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
MultipleSelecti
onTest.java
public class MultipleSelectionTest extends JFrame {
private JList colorList, copyList;
private JButton copyButton;
private final String colorNames[] = { "Black", "Blue", "Cyan",
"Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange",
"Pink", "Red", "White", "Yellow" };
Lines 10-12 and 24
Lines 26-27
// set up GUI
public MultipleSelectionTest()
{
super( "Multiple Selection Lists" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JList colorList
colorList = new JList( colorNames );
colorList.setVisibleRowCount( 5 );
colorList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
container.add( new JScrollPane( colorList ) );
Use colorNames array
to populate JList
JList colorList
allows multiple selections
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
// create copy button and register its listener
copyButton = new JButton( "Copy >>>" );
copyButton.addActionListener(
new ActionListener() {
MultipleSelecti
onTest.java
// anonymous inner class
// handle button event
public void actionPerformed( ActionEvent event )
{
// place selected values in copyList
copyList.setListData( colorList.getSelectedValues() );
}
} // end anonymous inner class
); // end call to addActionListener
Line 40
Lines 54-55
When user presses JButton, JList
copyList adds items that user
selected from JList colorList
container.add( copyButton );
// set up JList copyList
copyList = new JList( );
copyList.setVisibleRowCount( 5 );
copyList.setFixedCellWidth( 100 );
copyList.setFixedCellHeight( 15 );
copyList.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION );
container.add( new JScrollPane( copyList ) );
JList colorList
allows single selections
57
58
59
60
61
62
63
64
65
66
67
68
69
setSize( 300, 130 );
setVisible( true );
} // end constructor MultipleSelectionTest
public static void main( String args[] )
{
MultipleSelectionTest application = new MultipleSelectionTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MultipleSelectionTest
MultipleSelecti
onTest.java
13.12 Mouse Event Handling
• Event-listener interfaces for mouse events
– MouseListener
– MouseMotionListener
– Listen for MouseEvents
Fig. 13.16 MouseListener and
MouseMotionListener interface methods
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.
public void mouseReleased( MouseEvent event )
Called when a mouse button is released after being pressed. This event is always
preceded by a mousePressed event.
public void mouseEntered( MouseEvent event )
Called when the mouse cursor enters the bounds of a component.
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 drag began.
public void mouseMoved( MouseEvent event )
Called when the mouse is moved when the mouse cursor on a component. All move
events are sent to the component over which the mouse is currently positioned.
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
// Fig. 13.17: MouseTracker.java
// Demonstrating mouse events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
MouseTracker.ja
va
public class MouseTracker extends JFrame
implements MouseListener, MouseMotionListener {
Lines 20-21
private JLabel statusBar;
// set up GUI and register mouse event handlers
public MouseTracker()
{
super( "Demonstrating Mouse Events" );
statusBar = new JLabel();
getContentPane().add( statusBar, BorderLayout.SOUTH );
addMouseListener( this );
addMouseMotionListener( this );
setSize( 275, 100 );
setVisible( true );
}
Register JFrame to
events
// listens for own mouse and
receive mouse
// mouse-motion events
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// MouseListener event handlers
// handle event when mouse released immediately after press
public void mouseClicked( MouseEvent event )
{
statusBar.setText( "Clicked at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse pressed
public void mousePressed( MouseEvent event )
{
statusBar.setText( "Pressed at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse released after dragging
public void mouseReleased( MouseEvent event )
{
statusBar.setText( "Released at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse enters area
public void mouseEntered( MouseEvent event )
{
Invoked when user presses
and releases mouse button
MouseTracker.ja
va
Line 29
Invoked when user
Line 36
presses mouse button
Line 43
Line 50
Invoked when user releases mouse
button after dragging mouse
Invoked when mouse
cursor enters JFrame
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
statusBar.setText( "Mouse entered at [" + event.getX() +
", " + event.getY() + "]" );
getContentPane().setBackground( Color.GREEN );
}
// handle event when mouse exits area
public void mouseExited( MouseEvent event )
{
statusBar.setText( "Mouse outside window" );
getContentPane().setBackground( Color.WHITE );
}
// MouseMotionListener event handlers
// handle event when user drags mouse with button pressed
public void mouseDragged( MouseEvent event )
{
statusBar.setText( "Dragged at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when user moves mouse
public void mouseMoved( MouseEvent event )
{
statusBar.setText( "Moved at [" + event.getX() +
", " + event.getY() + "]" );
}
MouseTracker.ja
va
Invoked when mouse
cursor exits Line
JFrame
58
Line 66
Line 73
Invoked when user
drags mouse cursor
Invoked when user
moves mouse cursor
79
80
81
82
83
84
85
public static void main( String args[] )
{
MouseTracker application = new MouseTracker();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
MouseTracker.ja
va
13.13 Adapter Classes
• Adapter class
– Implements interface
– Provides default implementation of each interface method
– Used when all methods in interface is not needed
Fig. 13.18
Event-adapter classes and the interfaces
they implement in package java.awt.event
Event-adapter class
ComponentAdapter
Implements interface
ComponentListener
ContainerAdapter
ContainerListener
FocusAdapter
FocusListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter
MouseMotionListener
WindowAdapter
WindowListener
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
// Fig. 13.19: Painter.java
// Using class MouseMotionAdapter.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Painter.java
Line 22
public class Painter extends JFrame {
private int pointCount = 0;
// array of 1000 java.awt.Point references
private Point points[] = new Point[ 1000 ];
// set up GUI and register mouse event handler
public Painter()
{
super( "A simple paint program" );
// create a label and place it in SOUTH of BorderLayout
getContentPane().add( new JLabel( "Drag the mouse to draw" ),
BorderLayout.SOUTH );
addMouseMotionListener(
new MouseMotionAdapter() {
Register MouseMotionListener to
listen for window’s mouse-motion events
// anonymous inner class
26
27
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
// store drag coordinates and repaint
public void mouseDragged( MouseEvent event )
{
if ( pointCount < points.length ) {
points[ pointCount ] = event.getPoint();
++pointCount;
repaint();
}
}
Override method mouseDragged,
but not method mouseMoved
Painter.java
Store coordinates where mouse was
Line 27
dragged, then repaint JFrame
} // end anonymous inner class
Line 30
Line 51
); // end call to addMouseMotionListener
setSize( 300, 150 );
setVisible( true );
} // end Painter constructor
// draw oval in a 4-by-4 bounding box at specified location on window
public void paint( Graphics g )
{
super.paint( g ); // clears drawing area
for ( int i = 0; i < points.length && points[ i ] != null; i++ )
g.fillOval( points[ i ].x, points[ i ].y, 4, 4 );
}
Draw circle of diameter 4
where user dragged cursor
53
54
55
56
57
58
59
60
public static void main( String args[] )
{
Painter application = new Painter();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class Painter
Painter.java
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
// Fig. 13.20: MouseDetails.java
// Demonstrating mouse clicks and distinguishing between mouse buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseDetails extends JFrame {
private int xPos, yPos;
MouseDetails.ja
va
Line 15
// set title bar String; register mouse listener; size and show window
public MouseDetails()
{
super( "Mouse clicks and buttons" );
addMouseListener( new MouseClickHandler() );
setSize( 350, 150 );
setVisible( true );
}
// draw String at location where mouse was clicked
public void paint( Graphics g )
{
// call superclass paint method
super.paint( g );
Register mouse listener
27
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
g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]",
xPos, yPos );
}
MouseDetails.ja
va
public static void main( String args[] )
{
MouseDetails application = new MouseDetails();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// inner class to handle mouse events
private class MouseClickHandler extends MouseAdapter {
Line 41
Lines 43-44
Invoke method mouseClicked
when user clicks mouse
Line 46
// handle mouse click event and determine which button was pressed
public void mouseClicked( MouseEvent event )
Line 48
Store mouse-cursor coordinates
{
where mouse was clicked
xPos = event.getX();
51 of
Determine Line
number
yPos = event.getY();
times
user has clicked mouse
String title = "Clicked " + event.getClickCount() + " time(s)";
if ( event.isMetaDown() ) // right mouse button
title += " with right mouse button";
else if ( event.isAltDown() ) // middle mouse button
title += " with center mouse button";
Determine if user clicked
right mouse button
Determine if user clicked
middle mouse button
53
54
55
56
57
58
59
60
61
62
63
64
else // left mouse button
title += " with left mouse button";
setTitle( title );
repaint();
// set title bar of window
} // end method mouseClicked
} // end private inner class MouseClickHandler
} // end class MouseDetails
MouseDetails.ja
va
Fig. 13.21 InputEvent methods that help distinguish
among left-, center- and right-mouse-button clicks
InputEvent method
isMetaDown()
Description
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.
13.14 Key Event Handling
• Interface KeyListener
– Handles key events
• Generated when keys on keyboard are pressed and released
• KeyEvent
– Contains virtual key code that represents key
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
// Fig. 13.22: KeyDemo.java
// Demonstrating keystroke events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyDemo extends JFrame implements KeyListener {
private String line1 = "", line2 = "", line3 = "";
private JTextArea textArea;
KeyDemo.java
Line 23
// set up GUI
public KeyDemo()
{
super( "Demonstrating Keystroke Events" );
// set up JTextArea
textArea = new JTextArea( 10, 15 );
textArea.setText( "Press any key on the keyboard..." );
textArea.setEnabled( false );
textArea.setDisabledTextColor( Color.BLACK );
getContentPane().add( textArea );
addKeyListener( this );
setSize( 350, 100 );
setVisible( true );
// allow frame to process
Key events
Register
JFrame
for key events
27
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
} // end KeyDemo constructor
// handle press of any key
public void keyPressed( KeyEvent event )
Called when
{
line1 = "Key pressed: " + event.getKeyText( event.getKeyCode() );
setLines2and3( event );
}
KeyDemo.java
user presses key
Line 31
Line 33 and 40
Return virtual key code
// handle release of any key
public void keyReleased( KeyEvent event )
Called when
{
line1 = "Key released: " + event.getKeyText( event.getKeyCode() );
setLines2and3( event );
}
// handle press of an action key
public void keyTyped( KeyEvent event )
{
line1 = "Key typed: " + event.getKeyChar();
setLines2and3( event );
}
// set second and third lines of output
private void setLines2and3( KeyEvent event )
{
Line 38
user releases
key
Line 45
Called when user types key
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
line2 = "This key is " + ( event.isActionKey() ? "" : "not " ) +
"an action key";
String temp = event.getKeyModifiersText( event.getModifiers() );
line3 = "Modifier keys pressed: " +
( temp.equals( "" ) ? "none" : temp );
textArea.setText( line1 + "\n" + line2 + "\n" + line3
Line 57
Determine if modifier keys (e.g., Alt,
Ctrl, Meta and Shift) were used
+ "\n" );
}
public static void main( String args[] )
{
KeyDemo application = new KeyDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class KeyDemo
KeyDemo.java
KeyDemo.java
13.15 Layout Managers
• Layout managers
–
–
–
–
–
Provided for arranging GUI components
Provide basic layout capabilities
Processes layout details
Programmer can concentrate on basic “look and feel”
Interface LayoutManager
Fig. 13.23 Layout managers
Layout manager
FlowLayout
Description
BorderLayout
Default for the content panes of JFrames (and other windows) and
JApplets. Arranges the components into five areas: NORTH, SOUTH,
EAST, WEST and CENTER.
GridLayout
Arranges the components into rows and columns.
Default for java.awt.Applet, java.awt.Panel and
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.
13.15.1 FlowLayout
• FlowLayout
– Most basic layout manager
– GUI components placed in container from left to right
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
// Fig. 13.24: FlowLayoutDemo.java
// Demonstrating FlowLayout alignments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FlowLayoutDemo extends JFrame {
private JButton leftButton, centerButton, rightButton;
private Container container;
private FlowLayout layout;
FlowLayoutDemo.
java
Lines 17 and 21
// set up GUI and register button listeners
public FlowLayoutDemo()
{
super( "FlowLayout Demo" );
layout = new FlowLayout();
// get content pane and set its layout
container = getContentPane();
container.setLayout( layout );
// set up leftButton and register listener
leftButton = new JButton( "Left" );
container.add( leftButton );
Set layout as FlowLayout
26
27
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
leftButton.addActionListener(
new ActionListener() {
// anonymous inner class
// process leftButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );
// realign attached components
layout.layoutContainer( container );
}
FlowLayoutDemo.
java
Line 33
Line 53
When user presses
left JButton, left
align components
} // end anonymous inner class
); // end call to addActionListener
// set up centerButton and register listener
centerButton = new JButton( "Center" );
container.add( centerButton );
centerButton.addActionListener(
new ActionListener() {
// anonymous inner class
// process centerButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
When user presses
center JButton,
center components
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// realign attached components
layout.layoutContainer( container );
}
}
FlowLayoutDemo.
java
);
// set up rightButton and register listener
rightButton = new JButton( "Right" );
container.add( rightButton );
rightButton.addActionListener(
new ActionListener() {
// anonymous inner class
// process rightButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );
// realign attached components
layout.layoutContainer( container );
}
}
);
setSize( 300, 75 );
setVisible( true );
Line 71
When user presses
right JButton,
right components
81
82
83
84
85
86
87
88
89
90
} // end constructor FlowLayoutDemo
public static void main( String args[] )
{
FlowLayoutDemo application = new FlowLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class FlowLayoutDemo
FlowLayoutDemo.
java
13.15.2 BorderLayout
• BorderLayout
– Arranges components into five regions
• NORTH
• SOUTH
• EAST
• WEST
• CENTER
(top of container)
(bottom of container)
(left of container)
(right of container)
(center of container)
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
// Fig. 13.25: BorderLayoutDemo.java
// Demonstrating BorderLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
BorderLayoutDem
o.java
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton buttons[];
private final String names[] = { "Hide North", "Hide South",
"Hide East", "Hide West", "Hide Center" };
private BorderLayout layout;
Lines 18 and 22
// set up GUI and event handling
public BorderLayoutDemo()
{
super( "BorderLayout Demo" );
layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( layout );
// instantiate button objects
buttons = new JButton[ names.length ];
Set layout as BorderLayout with
5-pixel horizontal and vertical gaps
27
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
for ( int count = 0; count < names.length; count++ ) {
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
}
// place buttons in BorderLayout; order not important
container.add( buttons[ 0 ], BorderLayout.NORTH );
container.add( buttons[ 1 ], BorderLayout.SOUTH );
container.add( buttons[ 2 ], BorderLayout.EAST );
container.add( buttons[ 3 ], BorderLayout.WEST );
container.add( buttons[ 4 ], BorderLayout.CENTER );
BorderLayoutDem
o.java
Lines 33-37
Place JButtons in regions
specified by BorderLayout
Lines 50 and 52
setSize( 300, 200 );
setVisible( true );
} // end constructor BorderLayoutDemo
// handle button events
public void actionPerformed( ActionEvent event )
{
for ( int count = 0; count < buttons.length; count++ )
if ( event.getSource() == buttons[ count ] )
buttons[ count ].setVisible( false );
else
buttons[ count ].setVisible( true );
When JButtons are “invisible,”
they are not displayed on screen,
and BorderLayout rearranges
53
54
55
56
57
58
59
60
61
62
63
64
// re-layout the content pane
layout.layoutContainer( getContentPane() );
}
public static void main( String args[] )
{
BorderLayoutDemo application = new BorderLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class BorderLayoutDemo
BorderLayoutDem
o.java
BorderLayoutDem
o.java
13.15.3 GridLayout
• GridLayout
– Divides container into grid of specified row an columns
– Components are added starting at top-left cell
• Proceed left-to-fight until row is full
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
// Fig. 13.26: GridLayoutDemo.java
// Demonstrating GridLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
GridLayoutDemo.
java
public class GridLayoutDemo extends JFrame implements ActionListener {
private JButton buttons[];
private final String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true;
private Container container;
private GridLayout grid1, grid2;
// set up GUI
public GridLayoutDemo()
{
super( "GridLayout Demo" );
// set up layouts
grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );
// get content pane and set its layout
container = getContentPane();
container.setLayout( grid1 );
Line 21
Line 22
Create GridLayout grid1
with 2 rows and 3 columns
Create GridLayout grid2
with 3 rows and 2 columns
27
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
// create and add buttons
buttons = new JButton[ names.length ];
for ( int count =
buttons[ count
buttons[ count
container.add(
}
0; count < names.length; count++ ) {
] = new JButton( names[ count ] );
].addActionListener( this );
buttons[ count ] );
setSize( 300, 150 );
setVisible( true );
} // end constructor GridLayoutDemo
// handle button events by toggling between layouts
public void actionPerformed( ActionEvent event )
{
Toggle current
if ( toggle )
GridLayout when
container.setLayout( grid2 );
else
user presses JButton
container.setLayout( grid1 );
toggle = !toggle;
// set toggle to opposite value
container.validate();
}
GridLayoutDemo.
java
Lines 46 and 48
53
54
55
56
57
58
59
60
public static void main( String args[] )
{
GridLayoutDemo application = new GridLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class GridLayoutDemo
GridLayoutDemo.
java
13.16 Panels
• Panel
– Helps organize components
– Class JPanel is JComponent subclass
– May have components (and other panels) added to them
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
// Fig. 13.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[];
PanelDemo.java
Line 23
// set up GUI
public PanelDemo()
{
super( "Panel Demo" );
// get content pane
Container container = getContentPane();
// create buttons array
buttons = new JButton[ 5 ];
// set up panel and set its layout
buttonPanel = new JPanel();
Create JPanel
buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );
to hold JButtons
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// create and add buttons
for ( int count = 0; count < buttons.length; count++ ) {
buttons[ count ] = new JButton( "Button " + ( count + 1 ) );
buttonPanel.add( buttons[ count ] );
Add
}
Line 29
container.add( buttonPanel, BorderLayout.SOUTH );
setSize( 425, 150 );
setVisible( true );
Line 32
Add JPanel to SOUTH
region of Container
} // end constructor PanelDemo
public static void main( String args[] )
{
PanelDemo application = new PanelDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class PanelDemo
JButtons
to JPanel
PanelDemo.java
13.17 (Optional Case Study) Thinking About
Objects: Use Cases
• Use case
– Represents capabilities that systems provide to clients
• Automated-teller-machine use cases
– “Deposit Money,” “Withdraw Money,” “Transfer Funds”
13.17 (Optional Case Study) Thinking About
Objects: Use Cases
• Use-case diagram
– Models use cases in system
– Facilitates system-requirements gathering
– Notation
• Stick figure represents actor
– Actor represents set of roles that external entity can play
• System box (rectangle) contains system use cases
• Ovals represent use cases
13.17 (Optional Case Study) Thinking About
Objects: Use Cases
• Elevator-simulation use cases
– “Create Person”
• From user’s perspective
– “Relocate Person” (move to other floor)
• From Person’s perspective
• Constructing GUI
– Use “Create Person” use case
Fig. 13.28 Use case diagram for elevator
simulation from user’s perspective
Create Person
User
Fig. 13.29 Use case diagram from the
perspective of a Person
Relocate Person
Person