Lecture 8 GUI Part 5
© 2003 Prentice Hall, Inc. All rights reserved.
14.5 JSlider
• JSlider
– Enable users to select from range of integer values
– Several features
• Tick marks (major and minor)
• Snap-to ticks
• Orientation (horizontal and vertical)
© 2003 Prentice Hall, Inc. All rights reserved.
Fig. 14.6 JSlider component with horizontal
orientation
thumb
tick mark
© 2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 14.7: OvalPanel.java Outline
2 // A customized JPanel class.
3 import java.awt.*;
4 import javax.swing.*; OvalPanel.java
5
6 public class OvalPanel extends JPanel {
7 private int diameter = 10; Line 14
8
9 // draw an oval of the specified diameter Line 18
10 public void paintComponent( Graphics g )
11 {
12 super.paintComponent( g );
13
14 g.fillOval( 10, 10, diameter, diameter ); Draw filled oval of diameter
15 }
16
17 // validate and set diameter, then repaint
18 public void setDiameter( int newDiameter ) Set diameter, then repaint
19 {
20 // if diameter invalid, default to 10
21 diameter = ( newDiameter >= 0 ? newDiameter : 10 );
22 repaint();
23 }
24
© 2003 Prentice Hall, Inc.
All rights reserved.
25 // used by layout manager to determine preferred size Outline
26 public Dimension getPreferredSize()
27 {
28 return new Dimension( 200, 200 ); OvalPanel.java
29 }
30
31 // used by layout manager to determine minimum size
32 public Dimension getMinimumSize()
33 {
34 return getPreferredSize();
35 }
36
37 } // end class OvalPanel
© 2003 Prentice Hall, Inc.
All rights reserved.
1 // Fig. 14.8: SliderDemo.java Outline
2 // Using JSliders to size an oval.
3 import java.awt.*;
4 import java.awt.event.*; SliderDemo.java
5 import javax.swing.*;
6 import javax.swing.event.*;
7 Lines 18-19
8 public class SliderDemo extends JFrame {
9 private JSlider diameterSlider; Lines 22-23
10 private OvalPanel myPanel;
11
12 // set up GUI
13 public SliderDemo()
14 { Instantiate OvalPanel object
15 super( "Slider Demo" ); and set background to yellow
16
17 // set up OvalPanel
18 myPanel = new OvalPanel();
Instantiate horizontal JSlider object
19 myPanel.setBackground( Color.YELLOW );
20
with min. value of 0, max. value of 200
21 // set up JSlider to control diameter value and initial thumb location at 10
22 diameterSlider =
23 new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 );
24 diameterSlider.setMajorTickSpacing( 10 );
25 diameterSlider.setPaintTicks( true );
26
© 2003 Prentice Hall, Inc.
All rights reserved.
27 // register JSlider event listener Register anonymous Outline
28 diameterSlider.addChangeListener( ChangeListener object
29
to handle JSlider events
30 new ChangeListener() { // anonymous inner class SliderDemo.java
31
32 // handle change in slider value
33 public void stateChanged( ChangeEvent e ) Line 28
34 {
35 myPanel.setDiameter( diameterSlider.getValue() ); Line 35
36 }
37
38 } // end anonymous inner class
When user accesses JSlider,
39 set OvalPanel’s diameter
40 ); // end call to addChangeListener according to JSlider value
41
42 // attach components to content pane
43 Container container = getContentPane();
44 container.add( diameterSlider, BorderLayout.SOUTH );
45 container.add( myPanel, BorderLayout.CENTER );
46
47 setSize( 220, 270 );
48 setVisible( true );
49
50 } // end constructor SliderDemo
51
© 2003 Prentice Hall, Inc.
All rights reserved.
52 public static void main( String args[] ) Outline
53 {
54 SliderDemo application = new SliderDemo();
55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); SliderDemo.java
56 }
57
58 } // end class SliderDemo
© 2003 Prentice Hall, Inc.
All rights reserved.
14.6 Windows: Additional Notes
• JFrame
– Windows with title bar and border
– Subclass of java.awt.Frame
• Subclass of java.awt.Window
– Heavyweight component
– Three operations when user closes window
• DISPOSE_ON_CLOSE
• DO_NOTHING_ON_CLOSE
• HIDE_ON_CLOSE
© 2003 Prentice Hall, Inc. All rights reserved.
14.7 Using Menus with Frames
• Menus
– Allows for performing actions with cluttering GUI
– Contained by menu bar
• JMenuBar
– Comprised of menu items
• JMenuItem
© 2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 14.9: MenuTest.java Outline
2 // Demonstrating menus
3 import java.awt.*;
4 import java.awt.event.*; MenuTest.java
5 import javax.swing.*;
6
7 public class MenuTest extends JFrame { Line 22
8 private final Color colorValues[] =
9 { Color.BLACK, Color.BLUE, Color.RED, Color.GREEN };
10 private JRadioButtonMenuItem colorItems[], fonts[];
11 private JCheckBoxMenuItem styleItems[];
12 private JLabel displayLabel;
13 private ButtonGroup fontGroup, colorGroup;
14 private int style;
15
16 // set up GUI
17 public MenuTest()
18 {
19 super( "Using JMenus" );
20
21 // set up File menu and its menu items
22 JMenu fileMenu = new JMenu( "File" ); Instantiate File JMenu
23 fileMenu.setMnemonic( 'F' );
24
© 2003 Prentice Hall, Inc.
All rights reserved.
25 // set up About... menu item Outline
26 JMenuItem aboutItem = new JMenuItem( "About..." );
27 aboutItem.setMnemonic( 'A' );
28 fileMenu.add( aboutItem );
Instantiate About… JMenuItem
29 aboutItem.addActionListener( to be placed in fileMenu MenuTest.java
30
31 new ActionListener() { // anonymous inner class Line 26
32
33 // display message dialog when user selects About... Lines 36-38
34 public void actionPerformed( ActionEvent event )
35 {
36 JOptionPane.showMessageDialog( MenuTest.this,
Line 46
37 "This is an example\nof using menus",
38 "About", JOptionPane.PLAIN_MESSAGE );
39 }
Whenuser selects About…
40 JMenuItem, display message
41 } // end anonymous inner class dialog with appropriate text
42
43 ); // end call to addActionListener
44
45 // set up Exit menu item
Instantiate Exit JMenuItem
46 JMenuItem exitItem = new JMenuItem( "Exit" );
47 exitItem.setMnemonic( 'x' ); to be placed in fileMenu
48 fileMenu.add( exitItem );
49 exitItem.addActionListener(
50
© 2003 Prentice Hall, Inc.
All rights reserved.
51 new ActionListener() { // anonymous inner class Outline
52
53 // terminate application when user clicks exitItem
54 public void actionPerformed( ActionEvent event ) MenuTest.java
55 {
56 System.exit( 0 ); user selects Exit
When
57 } Line 56
JMenuItem, exit system
58
59 } // end anonymous inner class Line 64
60
61 ); // end call to addActionListener
62
Line 69
63 // create menu bar and attach it to MenuTest window
64 JMenuBar bar = new JMenuBar();
65 setJMenuBar( bar ); Instantiate JMenuBar
66 bar.add( fileMenu ); to contain JMenus
67
68 // create Format menu, its submenus and menu items
69 JMenu formatMenu = new JMenu( "Format" ); Instantiate Format JMenu
70 formatMenu.setMnemonic( 'r' );
71
72 // create Color submenu
73 String colors[] = { "Black", "Blue", "Red", "Green" };
74
© 2003 Prentice Hall, Inc.
All rights reserved.
Instantiate Color JMenu
75 JMenu colorMenu = new JMenu( "Color" );
(submenu of Format JMenu)
Outline
76 colorMenu.setMnemonic( 'C' );
77
78 colorItems = new JRadioButtonMenuItem[ colors.length ]; MenuTest.java
79 colorGroup = new ButtonGroup();
80 ItemHandler itemHandler = new ItemHandler();
81 Line 75
82 // create color radio button menu items
83 for ( int count = 0; count < colors.length; count++ ) { Lines 78-79
84 colorItems[ count ] = Instantiate
85 new JRadioButtonMenuItem( colors[ count ] ); JRadioButtonMenuItems
Line 96 for
86 colorMenu.add( colorItems[ count ] );
Color JMenu and ensure that only
87 colorGroup.add( colorItems[ count ] );
88 one menu item is selected at a time
colorItems[ count ].addActionListener( itemHandler );
89 }
90
91 // select first Color menu item
92 colorItems[ 0 ].setSelected( true );
93
94 // add format menu to menu bar
95 formatMenu.add( colorMenu );
96 formatMenu.addSeparator();
Separator places line
97 between JMenuItems
98 // create Font submenu
99 String fontNames[] = { "Serif", "Monospaced", "SansSerif" };
100
© 2003 Prentice Hall, Inc.
All rights reserved.
Instantiate Font JMenu
101 JMenu fontMenu = new JMenu( "Font" );
(submenu of Format JMenu)
Outline
102 fontMenu.setMnemonic( 'n' );
103
104 fonts = new JRadioButtonMenuItem[ fontNames.length ]; MenuTest.java
105 fontGroup = new ButtonGroup();
106
107 // create Font radio button menu items Line 101
108 for ( int count = 0; count < fonts.length; count++ ) {
109 fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] ); Lines 104-105
110 fontMenu.add( fonts[ count ] );
111 fontGroup.add( fonts[ count ] ); Instantiate
112 fonts[ count ].addActionListener( itemHandler );
JRadioButtonMenuItems for
113 }
114
Font JMenu and ensure that only
115 // select first Font menu item one menu item is selected at a time
116 fonts[ 0 ].setSelected( true );
117
118 fontMenu.addSeparator();
119
120 // set up style menu items
121 String styleNames[] = { "Bold", "Italic" };
122
123 styleItems = new JCheckBoxMenuItem[ styleNames.length ];
124 StyleHandler styleHandler = new StyleHandler();
125
© 2003 Prentice Hall, Inc.
All rights reserved.
126 // create style checkbox menu items Outline
127 for ( int count = 0; count < styleNames.length; count++ ) {
128 styleItems[ count ] =
129 new JCheckBoxMenuItem( styleNames[ count ] ); MenuTest.java
130 fontMenu.add( styleItems[ count ] );
131 styleItems[ count ].addItemListener( styleHandler );
132 }
133
134 // put Font menu in Format menu
135 formatMenu.add( fontMenu );
136
137 // add Format menu to menu bar
138 bar.add( formatMenu );
139
140 // set up label to display text
141 displayLabel = new JLabel( "Sample Text", SwingConstants.CENTER );
142 displayLabel.setForeground( colorValues[ 0 ] );
143 displayLabel.setFont( new Font( "Serif", Font.PLAIN, 72 ) );
144
145 getContentPane().setBackground( Color.CYAN );
146 getContentPane().add( displayLabel, BorderLayout.CENTER );
147
148 setSize( 500, 200 );
149 setVisible( true );
150
151 } // end constructor
152
© 2003 Prentice Hall, Inc.
All rights reserved.
153 public static void main( String args[] ) Outline
154 {
155 MenuTest application = new MenuTest();
156 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); MenuTest.java
157 }
Invoked when user selects JMenuItem
158
159 // inner class to handle action events from menu items Line 163
160 private class ItemHandler implements ActionListener {
161 Lines 168 and 176
162 // process color and font selections
163 public void actionPerformed( ActionEvent event ) Determine which font or 169
colorand
164 {
Lines 177-
menu generated178
event
165 // process color selection
166 for ( int count = 0; count < colorItems.length; count++ )
167
168 if ( colorItems[ count ].isSelected() ) {
169 displayLabel.setForeground( colorValues[ count ] );
170 break;
171 }
Set font or color of JLabel,
172
173 // process font selection respectively
174 for ( int count = 0; count < fonts.length; count++ )
175
176 if ( event.getSource() == fonts[ count ] ) {
177 displayLabel.setFont(
178 new Font( fonts[ count ].getText(), style, 72 ) );
179 break;
180 }
© 2003 Prentice Hall, Inc.
All rights reserved.
181 Outline
182 repaint();
183
184 } // end method actionPerformed MenuTest.java
185
186 } // end class ItemHandler
187 Line 192
Invoked when user selects
188 JCheckBoxMenuItem
// inner class to handle item events from check box menu items
189 private class StyleHandler implements ItemListener { Lines 197-202
190
191 // process font style selections
192 public void itemStateChanged( ItemEvent e )
193 {
194 style = 0;
195
196 // check for bold selection
197 if ( styleItems[ 0 ].isSelected() )
198 style += Font.BOLD;
199 Determine new font style
200 // check for italic selection
201 if ( styleItems[ 1 ].isSelected() )
202 style += Font.ITALIC;
203
204 displayLabel.setFont(
205 new Font( displayLabel.getFont().getName(), style, 72 ) );
© 2003 Prentice Hall, Inc.
All rights reserved.
206 Outline
207 repaint();
208 }
209 MenuTest.java
210 } // end class StyleHandler
211
212 } // end class MenuTest
© 2003 Prentice Hall, Inc.
All rights reserved.
14.8 JPopupMenu
• Context-sensitive popup menus
– JPopupMenu
– Menu generated depending on which component is accessed
© 2003 Prentice Hall, Inc. All rights reserved.
1 // Fig. 14.10: PopupTest.java Outline
2 // Demonstrating JPopupMenus
3 import java.awt.*;
4 import java.awt.event.*; PopupTest.java
5 import javax.swing.*;
6
7 public class PopupTest extends JFrame { Line 23
8 private JRadioButtonMenuItem items[];
9 private final Color colorValues[] =
10 { Color.BLUE, Color.YELLOW, Color.RED };
11 private JPopupMenu popupMenu;
12
13 // set up GUI
14 public PopupTest()
15 {
16 super( "Using JPopupMenus" );
17
18 ItemHandler handler = new ItemHandler();
19 String colors[] = { "Blue", "Yellow", "Red" };
20
21 // set up popup menu and its items
22 ButtonGroup colorGroup = new ButtonGroup();
23 popupMenu = new JPopupMenu(); Instantiate JPopupMenu object
24 items = new JRadioButtonMenuItem[ 3 ];
25
© 2003 Prentice Hall, Inc.
All rights reserved.
26 // construct each menu item and add to popup menu; also Outline
27 // enable event handling for each menu item
28 for ( int count = 0; count < items.length; count++ ) {
29 items[ count ] = new JRadioButtonMenuItem( colors[ count ] ); PopupTest.java
30 popupMenu.add( items[ count ] );
31 colorGroup.add( items[ count ] ); Create JRadioButtonMenuItem
32 items[ count ].addActionListener( handler ); Lines 29-32
objects to add to JPopupMenu
33 }
34 Lines 46 and 52
35 getContentPane().setBackground( Color.WHITE );
36
37 // declare a MouseListener for the window that displays
38 // a JPopupMenu when the popup trigger event occurs
39 addMouseListener(
40
41 new MouseAdapter() { // anonymous inner class
42
43 // handle mouse press event
44 public void mousePressed( MouseEvent event )
45 {
46 checkForTriggerEvent( event );
47 }
48
49 // handle mouse release event Determine whether popup-
50 public void mouseReleased( MouseEvent event ) trigger event occurred
51 { when user presses or
52 checkForTriggerEvent( event ); releases mouse button
53 }
© 2003 Prentice Hall, Inc.
All rights reserved.
54 Outline
55 // determine whether event should trigger popup menu
56 private void checkForTriggerEvent( MouseEvent event )
57 { PopupTest.java
58 if ( event.isPopupTrigger() )
59 popupMenu.show(
60 event.getComponent(), event.getX(), event.getY() ); Lines 59-60
61 }
62 Show JPopupMenu if
63 } // end anonymous inner clas popup-trigger occurred
64
65 ); // end call to addMouseListener
66
67 setSize( 300, 200 );
68 setVisible( true );
69
70 } // end constructor PopupTest
71
72 public static void main( String args[] )
73 {
74 PopupTest application = new PopupTest();
75 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
76 }
77
© 2003 Prentice Hall, Inc.
All rights reserved.
78 // private inner class to handle menu item events Outline
79 private class ItemHandler implements ActionListener {
80 Invoked when user selects
81 // process menu item selections PopupTest.java
JRadioButtonMenuItem
82 public void actionPerformed( ActionEvent event )
83 {
84 // determine which menu item was selected Line 82
85 for ( int i = 0; i < items.length; i++ )
86 if ( event.getSource() == items[ i ] ) { Line 87
87 getContentPane().setBackground( colorValues[ i ] );
88 return;
89 }
90 }
91
92 } // end private inner class ItemHandler
Determine which
93 JRadioButtonMenuItem was selected,
94 } // end class PopupTest then set window background color
© 2003 Prentice Hall, Inc.
All rights reserved.