Java GUI Programming - Department of Computer and Information

Download Report

Transcript Java GUI Programming - Department of Computer and Information

Department of Computer and Information Science,
School of Science, IUPUI
GUI Programming using Java
- GUI Components
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: [email protected]
Dale Roberts
JButton
Abstract Button
Component user clicks to trigger a specific action
Can be command button, check box, toggle button or
radio button
Button types are subclasses of class AbstractButton
2
Dale Roberts
JButton
Command button
Generates an ActionEvent when it is clicked
Created with class JButton
Text on the face of the button is called button label
3
Dale Roberts
1
// Fig. 11.15: ButtonFrame.java
2
// Creating JButtons.
3
import java.awt.FlowLayout;
4
import java.awt.event.ActionListener;
5
6
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
7
8
import javax.swing.JButton;
import javax.swing.Icon;
9
import javax.swing.ImageIcon;
Outline
10 import javax.swing.JOptionPane;
11
Declare two JButton instance
variables
12 public class ButtonFrame extends JFrame
13 {
14
private JButton plainJButton; // button with just text
15
private JButton fancyJButton; // button with icons
16
17
18
19
20
// ButtonFrame adds JButtons to JFrame
public ButtonFrame()
{
super( "Testing Buttons" );
21
22
23
24
25
Create new JButton
setLayout( new FlowLayout() ); // set frame layout
plainJButton = new JButton( "Plain Button" ); // Create
button two
withImageIcons
text
add( plainJButton ); // add plainJButton to JFrame
Create new JButton
26
27
28
Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) );
Icon bug2 = new ImageIcon( getClass().getResource( "bug2.gif" ) );
Set rollover icon for
fancyJButton = new JButton( "Fancy Button", bug1 ); // set image
29
30
fancyJButton.setRolloverIcon( bug2 ); // set rollover image
add( fancyJButton ); // add fancyJButton to JFrame
Dale Roberts
JButton
ButtonFram
e.java
(1 of 2)
4
31
32
// create new ButtonHandler for button event handling
33
34
ButtonHandler handler = new ButtonHandler();
fancyJButton.addActionListener( handler );
Create handler for buttons
35
36
plainJButton.addActionListener( handler );
} // end ButtonFrame constructor
37
38
39
Register
// inner class for button event handling
private class ButtonHandler implements ActionListener
40
{
41
42
// handle button event
public void actionPerformed( ActionEvent event )
43
{
44
45
46
47
Outline
event handlers
Inner class implements ActionListener
JOptionPane.showMessageDialog( ButtonFrame.this, String.format(
"You pressed: %s", event.getActionCommand() ) );
} // end method actionPerformed
Access outer class’s
} // end private inner class ButtonHandler
48 } // end class ButtonFrame
ButtonFram
e.java
(2 of 2)
instance using
this reference
Get text of JButton pressed
Dale Roberts
5
1
// Fig. 11.16: ButtonTest.java
2
// Testing ButtonFrame.
3
import javax.swing.JFrame;
Outline
4
5
public class ButtonTest
6
{
7
public static void main( String args[] )
8
{
9
ButtonFrame buttonFrame = new ButtonFrame(); // create ButtonFrame
10
buttonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
buttonFrame.setSize( 275, 110 ); // set frame size
12
buttonFrame.setVisible( true ); // display frame
13
} // end main
14 } // end class ButtonTest
Dale Roberts
ButtonTest.
java
(1 of 2)
6
Outline
Button
Test.ja
va
(2 of 2)
Dale Roberts
7
JButton
JButtons can have a rollover icon
Appears when mouse is positioned over a button
Added to a JButton with method setRolloverIcon
8
Dale Roberts
Software Engineering Observation 11.4
When used in an inner class, keyword
this refers to the current inner-class
object being manipulated. An innerclass method can use its outer-class
object’s this by preceding this with the
outer-class name and a dot, as in
ButtonFrame.this.
9
Dale Roberts
Buttons That Maintain State
State buttons
Swing contains three types of state buttons
JToggleButton, JCheckBox and JRadioButton
JCheckBox and JRadioButton are subclasses of
JToggleButton
10
Dale Roberts
JCheckBox
JCheckBox
Contains a check box label that appears to right of check
box by default
Generates an ItemEvent when it is clicked
ItemEvents are handled by an ItemListener
Passed to method itemStateChanged
Method isSelected returns whether check box is
selected (true) or not (false)
11
Dale Roberts
1
2
// Fig. 11.17: CheckBoxFrame.java
// Creating JCheckBox buttons.
3
4
import java.awt.FlowLayout;
import java.awt.Font;
5
import java.awt.event.ItemListener;
6
7
8
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
Outline
12
CheckBoxF
rame
.java
Declare two JCheckBox instance
(1 of 3)
9 import javax.swing.JCheckBox;
10
11 public class CheckBoxFrame extends JFrame
variables
12 {
13
private JTextField textField; // displays text in changing fonts
14
private JCheckBox boldJCheckBox; // to select/deselect bold
15
private JCheckBox italicJCheckBox; // to select/deselect italic
16
17
// CheckBoxFrame constructor adds JCheckBoxes to JFrame
18
19
20
public CheckBoxFrame()
{
super( "JCheckBox Test" );
21
22
setLayout( new FlowLayout() ); // set frame layout
23
// set up JTextField and set its font
24
25
26
textField = new JTextField( "Watch the font style change", 20 );
textField.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
add( textField ); // add textField to JFrame
Set font of text field
27
Dale Roberts
28
boldJCheckBox = new JCheckBox( "Bold" ); // create bold checkbox
29
italicJCheckBox = new JCheckBox( "Italic" ); // create italic
30
add( boldJCheckBox ); // add bold checkbox to JFrame
31
32
add( italicJCheckBox ); // add italic checkbox to JFrame
33
// register listeners for JCheckBoxes
34
35
36
CheckBoxHandler handler = new CheckBoxHandler();
boldJCheckBox.addItemListener( handler );
italicJCheckBox.addItemListener( handler );
Create event handler
} // end CheckBoxFrame constructor
38
39
40
// private inner class for ItemListener event handling
private class CheckBoxHandler implements ItemListener
Register event handler with
JCheckBoxes
{
CheckBoxF
rame
.java
(2 of 3)
Inner class implements
ItemListener
private int valBold = Font.PLAIN; // controls bold font style
43
44
private int valItalic = Font.PLAIN; // controls italic font style
45
46
47
// respond to checkbox events
public void itemStateChanged( ItemEvent event )
{
itemStateChanged method is
called when a JCheckBox is
clicked
48
// process bold checkbox events
49
50
51
if ( event.getSource() == boldJCheckBox )
valBold =
boldJCheckBox.isSelected() ? Font.BOLD : Font.PLAIN;
52
13
Create two JCheckBoxes
37
41
42
Outline
Test whether JCheckBox is
selected
Dale Roberts
53
// process italic checkbox events
54
if ( event.getSource() == italicJCheckBox )
55
56
valItalic =
Outline
14
Test source of the event
italicJCheckBox.isSelected() ? Font.ITALIC : Font.PLAIN;
57
58
// set text field font
59
textField.setFont(
60
61
62
isSelected method returns CheckBoxF
whether JCheckBox is selected rame
new Font( "Serif", valBold + valItalic, 14 ) );
} // end method itemStateChanged
} // end private inner class CheckBoxHandler
63 } // end class CheckBoxFrame
Dale Roberts
.java
(3 of 3)
1
// Fig. 11.18: CheckBoxTest.java
2
// Testing CheckBoxFrame.
3
import javax.swing.JFrame;
Outline
15
4
5
public class CheckBoxTest
6
{
7
public static void main( String args[] )
8
{
9
CheckBoxFrame checkBoxFrame = new CheckBoxFrame();
10
checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
checkBoxFrame.setSize( 275, 100 ); // set frame size
12
checkBoxFrame.setVisible( true ); // display frame
13
} // end main
14 } // end class CheckBoxTest
Dale Roberts
CheckBoxT
est
.java
JRadioButton
JRadioButton
Has two states – selected and unselected
Normally appear in a group in which only one radio button
can be selected at once
Group maintained by a ButtonGroup object
Declares method add to add a JRadioButton to group
Usually represents mutually exclusive options
16
Dale Roberts
1
// Fig. 11.19: RadioButtonFrame.java
2
// Creating radio buttons using ButtonGroup and JRadioButton.
3
import java.awt.FlowLayout;
4
import java.awt.Font;
5
6
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
7
8
import javax.swing.JFrame;
import javax.swing.JTextField;
9
import javax.swing.JRadioButton;
Outline
17
RadioButto
nFrame.jav
a
(1 of 3)
10 import javax.swing.ButtonGroup;
11
12 public class RadioButtonFrame extends JFrame
13 {
14
private JTextField textField; // used to display font changes
15
private Font plainFont; // font for plain text
16
17
18
19
20
private
private
private
private
private
21
22
23
24
private JRadioButton italicJRadioButton; // selects italic text
private JRadioButton boldItalicJRadioButton; // bold and italic
private ButtonGroup radioGroup; // buttongroup to hold radio buttons
25
// RadioButtonFrame constructor adds JRadioButtons to JFrame
26
27
28
public RadioButtonFrame()
{
super( "RadioButton Test" );
29
30
Declare four JRadioButtons
and a ButtonGroup to manage
them
Font boldFont; // font for bold text
Font italicFont; // font for italic text
Font boldItalicFont; // font for bold and italic text
JRadioButton plainJRadioButton; // selects plain text
JRadioButton boldJRadioButton; // selects bold text
setLayout( new FlowLayout() ); // set frame layout
Dale Roberts
31
32
textField = new JTextField( "Watch the font style change", 25 );
add( textField ); // add textField to JFrame
33
34
// create radio buttons
35
plainJRadioButton = new JRadioButton( "Plain", true );
36
37
38
boldJRadioButton = new JRadioButton( "Bold", false );
italicJRadioButton = new JRadioButton( "Italic", false );
boldItalicJRadioButton = new JRadioButton( "Bold/Italic", false );
39
40
add(
add(
41
42
43
44
45
46
add(
add( boldItalicJRadioButton ); // add bold and italic button
47
48
radioGroup.add( boldJRadioButton ); // add bold to group
radioGroup.add( italicJRadioButton ); // add italic to group
49
50
51
52
radioGroup.add( boldItalicJRadioButton ); // add bold and italic
// create font objects
plainFont = new Font( "Serif", Font.PLAIN, 14 );
53
boldFont = new Font( "Serif", Font.BOLD, 14 );
54
55
56
italicFont = new Font( "Serif", Font.ITALIC, 14 );
boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
textField.setFont( plainFont ); // set initial font to plain
Outline
RadioButto
nFrame
plainJRadioButton ); // add plain button to JFrame
.java
boldJRadioButton ); // add bold button to JFrame
(2 of 3)
italicJRadioButton ); // add italic button to
JFrame
Create
the four JRadioButtons
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup(); // create ButtonGroup
radioGroup.add( plainJRadioButton ); // add plain to group
Create the ButtonGroup
Add each JRadioButton to the
ButtonGroup
57
Dale Roberts
18
58
// register events for JRadioButtons
59
plainJRadioButton.addItemListener(
61
62
63
64
65
66
67
19
new RadioButtonHandler( plainFont ) );
60
Outline
boldJRadioButton.addItemListener(
new RadioButtonHandler( boldFont ) );
italicJRadioButton.addItemListener(
Register an event handler with each
JRadioButton
RadioButto
nFrame
.java
(3 of 3)
new RadioButtonHandler( italicFont ) );
boldItalicJRadioButton.addItemListener(
new RadioButtonHandler( boldItalicFont ) );
} // end RadioButtonFrame constructor
68
69
70
71
72
73
// private inner class to handle radio button events
private class RadioButtonHandler implements ItemListener
{
Event handler
private Font font; // font associated with this listener
inner class
implements ItemListener
74
75
76
77
78
public RadioButtonHandler( Font f )
{
font = f; // set the font of this listener
} // end constructor RadioButtonHandler
79
80
// handle radio button events
public void itemStateChanged( ItemEvent event )
81
82
{
83
} // end method itemStateChanged
When radio button is selected, the
text field’s font will be set to the
value passed to the constructor
textField.setFont( font ); // set font of textField
84
} // end private inner class RadioButtonHandler
85 } // end class RadioButtonFrame
Dale Roberts
1
// Fig. 11.20: RadioButtonTest.java
2
// Testing RadioButtonFrame.
3
import javax.swing.JFrame;
Outline
20
4
5
public class RadioButtonTest
6
{
7
public static void main( String args[] )
8
{
9
RadioButtonFrame radioButtonFrame = new RadioButtonFrame();
10
radioButtonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
radioButtonFrame.setSize( 300, 100 ); // set frame size
12
radioButtonFrame.setVisible( true ); // display frame
13
} // end main
14 } // end class RadioButtonTest
Dale Roberts
RadioButto
nTest
.java
JComboBox and Using an Anonymous Inner Class for
Event Handling
Combo box
Also called a drop-down list
Implemented by class JComboBox
Each item in the list has an index
setMaximumRowCount sets the maximum number of
rows shown at once
JComboBox provides a scrollbar and up and down arrows
to traverse list
21
Dale Roberts
Using an Anonymous Inner Class for Event Handling
Anonymous inner class
Special form of inner class
Declared without a name
Typically appears inside a method call
Has limited access to local variables
22
Dale Roberts
1
// Fig. 11.21: ComboBoxFrame.java
2
// Using a JComboBox to select an image to display.
3
import java.awt.FlowLayout;
4
import java.awt.event.ItemListener;
5
6
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
7
8
import javax.swing.JLabel;
import javax.swing.JComboBox;
9
import javax.swing.Icon;
Outline
23
ComboBox
Frame
.java
(1 of 2)
10 import javax.swing.ImageIcon;
11
12 public class ComboBoxFrame extends JFrame
13 {
14
private JComboBox imagesJComboBox; // combobox to hold names of icons
15
private JLabel label; // label to display selected icon
16
17
18
19
20
private String names[] =
variable
{ "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };
private Icon icons[] = {
new ImageIcon( getClass().getResource( names[ 0 ] ) ),
21
22
23
24
Declare JComboBox instance
new ImageIcon( getClass().getResource( names[ 1 ] ) ),
new ImageIcon( getClass().getResource( names[ 2 ] ) ),
new ImageIcon( getClass().getResource( names[ 3 ] ) ) };
25
// ComboBoxFrame constructor adds JComboBox to JFrame
26
27
28
public ComboBoxFrame()
{
super( "Testing JComboBox" );
29
30
setLayout( new FlowLayout() ); // set frame layout
Dale Roberts
31
32
imagesJComboBox = new JComboBox( names ); // set up JComboBox
Create
JComboBox
imagesJComboBox.setMaximumRowCount( 3 ); // display
three
rows
33
34
maximum row count
new ItemListener() // anonymous inner class
36
37
38
39
40
41
42
43
{
49
50
51
Outline
24
imagesJComboBox.addItemListener(
35
44
45
46
47
48
and set
Create anonymous inner class as
ComboBox
the event handler
// handle JComboBox event
public void itemStateChanged( ItemEvent event )
{
Declare method
// determine whether check box selected
itemStateChanged
if ( event.getStateChange() == ItemEvent.SELECTED )
label.setIcon( icons[
imagesJComboBox.getSelectedIndex()Test
] );state change of JComboBox
rame
.java
(2 of 2)
} // end method itemStateChanged
} // end anonymous inner class
); // end call to addItemListener
Method getSelectedIndex
locates selected item
add( imagesJComboBox ); // add combobox to JFrame
label = new JLabel( icons[ 0 ] ); // display first icon
add( label ); // add label to JFrame
} // end ComboBoxFrame constructor
52 } // end class ComboBoxFrame
Dale Roberts
1
// Fig. 11.22: ComboBoxTest.java
2
// Testing ComboBoxFrame.
3
import javax.swing.JFrame;
Outline
25
4
5
public class ComboBoxTest
6
{
7
public static void main( String args[] )
8
{
9
ComboBoxFrame comboBoxFrame = new ComboBoxFrame();
10
comboBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
12
13
comboBoxFrame.setSize( 350, 150 ); // set frame size
comboBoxFrame.setVisible( true ); // display frame
} // end main
14 } // end class ComboBoxTest
Scrollbar to scroll through the
items in the list
scroll arrows
scroll box
Dale Roberts
ComboBox
Test
.java
JList
List
Displays a series of items from which the user may select
one or more items
Implemented by class JList
Allows for single-selection lists or multiple-selection lists
A ListSelectionEvent occurs when an item is
selected
Handled by a ListSelectionListener and passed to method
valueChanged
26
Dale Roberts
1
// Fig. 11.23: ListFrame.java
2
// Selecting colors from a JList.
3
import java.awt.FlowLayout;
4
5
import java.awt.Color;
import javax.swing.JFrame;
6
import javax.swing.JList;
7
8
9
10
11
import
import
import
import
Outline
27
javax.swing.JScrollPane;
javax.swing.event.ListSelectionListener;
javax.swing.event.ListSelectionEvent;
javax.swing.ListSelectionModel;
ListFrame.j
ava
(1 of 2)
12 public class ListFrame extends JFrame
13 {
14
private JList colorJList; // list to display colors
15
16
private final String colorNames[] = { "Black", "Blue", "Cyan",
"Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
17
18
19
20
21
Declare JList instance
"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 };
22
23
24
25
// ListFrame constructor add JScrollPane containing JList to JFrame
public ListFrame()
{
26
27
28
super( "List Test" );
setLayout( new FlowLayout() ); // set frame layout
Dale Roberts
variable
29
30
colorJList = new JList( colorNames ); // create with colorNames
colorJList.setVisibleRowCount( 5 ); // display five rows at once
31
32
// do not allow multiple selections
33
colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Create JList
// add a JScrollPane containing JList to frame
add( new JScrollPane( colorJList ) );
Outline
Set selection mode of JList
colorJList.addListSelectionListener(
new ListSelectionListener() // anonymous innerAdd
class
JList to ScrollPane
{
add to application
// handle list selection events
public void valueChanged( ListSelectionEvent event )
{
getContentPane().setBackground(
colors[ colorJList.getSelectedIndex() ] );
} // end method valueChanged
} // end anonymous inner class
); // end call to addListSelectionListener
} // end ListFrame constructor
Get index of selected item
50 } // end class ListFrame
Dale Roberts
28
ListFrame.j
ava
(2 of 2)
and
1
// Fig. 11.24: ListTest.java
2
// Selecting colors from a JList.
3
import javax.swing.JFrame;
Outline
29
4
5
public class ListTest
6
{
7
public static void main( String args[] )
8
{
9
ListFrame listFrame = new ListFrame(); // create ListFrame
10
listFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
listFrame.setSize( 350, 150 ); // set frame size
12
listFrame.setVisible( true ); // display frame
13
} // end main
14 } // end class ListTest
Dale Roberts
ListTest.jav
a
Multiple-Selection Lists
Multiple-selection list
Enables users to select many items
Single interval selection allows only a continuous range of
items
Multiple interval selection allows any set of elements to be
selected
30
Dale Roberts
1
// Fig. 11.25: MultipleSelectionFrame.java
2
3
4
// Copying items from one List to another.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
5
6
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
7
import javax.swing.JList;
8
9
import javax.swing.JButton;
import javax.swing.JScrollPane;
Outline
31
10 import javax.swing.ListSelectionModel;
11
12 public class MultipleSelectionFrame extends JFrame
13 {
14
private JList colorJList; // list to hold color names
15
16
private JList copyJList; // list to copy color names into
private JButton copyJButton; // button to copy selected names
17
private final String colorNames[] = { "Black", "Blue", "Cyan",
"Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange",
"Pink", "Red", "White", "Yellow" };
18
19
20
21
22
23
24
25
// MultipleSelectionFrame constructor
public MultipleSelectionFrame()
{
super( "Multiple Selection Lists" );
setLayout( new FlowLayout() ); // set frame layout
26
Dale Roberts
Multiple
SelectionFr
ame
.java
(1 of 3)
27
28
colorJList = new JList( colorNames ); // holds names of all colors
colorJList.setVisibleRowCount( 5 ); // show five rows
29
30
colorJList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
31
add( new JScrollPane( colorJList ) ); // add listUse
with
scrollpane
a multiple
interval
32
33
34
35
copyJButton = new JButton( "Copy >>>" ); // create copy button
copyJButton.addActionListener(
list
36
new ActionListener() // anonymous inner class
37
38
39
{
40
41
42
43
44
45
46
// handle button event
public void actionPerformed( ActionEvent event )
Outline
32
selection
Multiple
SelectionFr
ame
.java
(2 of 3)
{
// place selected values in copyJList
copyJList.setListData( colorJList.getSelectedValues() );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
Use methods setListData and
getSelectedValues to copy
values from one JList to the
other
Dale Roberts
47
add( copyJButton ); // add copy button to JFrame
Outline
33
48
49
copyJList = new JList(); // create list to hold copied
Set cellcolor
widthnames
for presentation
50
copyJList.setVisibleRowCount( 5 ); // show 5 rows
51
copyJList.setFixedCellWidth( 100 ); // set width
52
copyJList.setFixedCellHeight( 15 ); // set height
53
54
55
56
Set cell height for presentation
copyJList.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION );
add( new JScrollPane( copyJList ) ); // add list with scrollpane
} // end MultipleSelectionFrame constructor
57 } // end class MultipleSelectionFrame
Set selection model to single
interval selection
Dale Roberts
Multiple
SelectionFr
ame
.java
(3 of 3)
1
// Fig. 11.26: MultipleSelectionTest.java
2
// Testing MultipleSelectionFrame.
3
import javax.swing.JFrame;
4
5
public class MultipleSelectionTest
6
7
8
Outline
34
{
public static void main( String args[] )
{
9
10
MultipleSelectionFrame multipleSelectionFrame =
new MultipleSelectionFrame();
11
12
multipleSelectionFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
13
14
15
multipleSelectionFrame.setSize( 350, 140 ); // set frame size
multipleSelectionFrame.setVisible( true ); // display frame
} // end main
16 } // end class MultipleSelectionTest
Dale Roberts
Multiple
SelectionTe
st
.java
Acknowledgements
Deitel, Java How to Program
Dale Roberts