Introduction To Java GUI
Introduction To Java GUI
Introduction To Java GUI
2
Simplest GUI programming:
JOptionPane
An option pane is a simple dialog box for graphical input/output
• advantages:
– simple
– flexible (in some ways)
– looks better than the black box of doom
• disadvantages:
– created with static methods;
not very object-oriented
– not very powerful (just simple dialog boxes)
3
Types of JOptionPanes
• public static void showMessageDialog(
Component parent, Object message)
Displays a message on a dialog
with an OK button.
JOptionPane examples 1
• showMessageDialog analogous to
System.out.println for displaying a simple
message
import javax.swing.*;
class MessageDialogExample {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"How's the weather?");
JOptionPane.showMessageDialog(null,
"Second message");
}
}
5
JOptionPane examples 2
• showConfirmDialog analogous to a
System.out.print that prints a question, then reading
an input value from the user (can only be one of the provided
choices)
import javax.swing.*;
class ConfirmDialogExample {
public static void main(String[] args) {
int choice = JOptionPane.showConfirmDialog(null,
"Erase your hard disk?");
if (choice == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Disk erased!");
} else {
JOptionPane.showMessageDialog(null, "Cancelled.");
}
}
}
6
JOptionPane examples 3
• showInputDialog analogous to a
System.out.print that prints a question, then reading
an input value from the user (can be any value)
import javax.swing.*;
class InputDialogExample {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null,
"What's yer name, pardner?");
JOptionPane.showMessageDialog(null, "Yeehaw, " + name);
}
}
Swing Overview
• Swing component inheritance hierarchy
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
• Labels
– Provide text instructions on a GUI
– Read-only text
– Programs rarely change a label's contents
– Class JLabel (subclass of JComponent)
• Methods
– Can declare label text in constructor
– myLabel.setToolTipText( "Text" )
• Displays "Text"in a tool tip when mouse over label
– myLabel.setText( "Text" )
– myLabel.getText()
JLabel
• Icon
– Object that implements interface Icon
– One class is ImageIcon (.gif and .jpeg images)
– Display an icon with setIcon method (of class JLabel)
• myLabel.setIcon( myIcon );
• myLabel.getIcon //returns current Icon
• Alignment
– Set of integer constants defined in interface
SwingConstants (javax.swing)
• SwingConstants.LEFT
• Use with JLabel methods
setHorizontalTextPosition and
setVerticalTextPosition
1 // Fig. 29.4: LabelTest.java
2 // Demonstrating the JLabel class.
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.*;
6 1. import
7 public class LabelTest extends JFrame {
8 private JLabel label1, label2, label3;
9
1.1 extend JFrame
10 public LabelTest()
11 { 1.2 Declarations
12 super( "Testing JLabel" );
13
14 Container c = getContentPane(); 1.3 Create container to
15 c.setLayout( new FlowLayout() ); hold labels
16
17 // JLabel constructor with a string argument
18 label1 = new JLabel( "Label with text" ); 1.4 Initialize JLabels
“
19 label1.setToolTipText( "This is label1" );
20 c.add( label1 );
21
22 // JLabel constructor with string, Icon and
23 // alignment arguments
24 Icon bug = new ImageIcon( "bug1.gif" );
25 label2 = new JLabel( "Label with text and icon",
26 bug, SwingConstants.LEFT );
27 label2.setToolTipText( "This is label2" );
28 c.add( label2 );
29
30 // JLabel constructor no arguments
31 label3 = new JLabel();
32 label3.setText( "Label with icon and text at bottom" );
33 label3.setIcon( bug );
34 label3.setHorizontalTextPosition(
35 SwingConstants.CENTER );
36 label3.setVerticalTextPosition( 1.4 Initialize JLabels
37 SwingConstants.BOTTOM );
38 label3.setToolTipText( "This is label3" );
39 c.add( label3 );
40
41 setSize( 275, 170 );
42 show();
43 }
44
45 public static void main( String args[] )
46 {
47 LabelTest app = new LabelTest();
48
57 }
58 }
<Anchor0>
Program Output
JTextArea
• Methods (continued)
– setEditable( boolean )
• If true, user can edit text
– getPassword
• Class JPasswordField
• Returns password as an array of type char
• Example
– Create JTextFields and a JPasswordField
– Create and register an event handler
• Displays a dialog box when Enter pressed
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
• Jbutton
– Text on face called button label
– Each button should have a different label
– Support display of Icons
JButton
• Constructors
Jbutton myButton = new JButton( "Button" );
Jbutton myButton = new JButton( "Button",
myIcon );
• Method
– setRolloverIcon( myIcon )
• Sets image to display when mouse over button
JCheckBox
• State buttons
– JToggleButton
• Subclasses JCheckBox, JRadioButton
– Have on/off (true/false) values
• Initialization
– JCheckBox myBox = new JCheckBox( "Title" );
• When JCheckBox changes
– ItemEvent generated
• Handled by an ItemListener, which must define
itemStateChanged
– Register with addItemListener
JCheckBox (II)
• ItemEvent methods
– getStateChange
• Returns ItemEvent.SELECTED or
ItemEvent.DESELECTED
JComboBox
• Methods
– getSelectedIndex
• Returns the index of the currently selected item
– setMaximumRowCount( n )
• Set the maximum number of elements to display when user
clicks combo box
• Scrollbar automatically provided
Demo
29.4 Event Handling Model
Program Output
1 // Fig. 29.13: ComboBoxTest.java
2 // Using a JComboBox to select an image to display.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 1. import
7 public class ComboBoxTest extends JFrame {
8 private JComboBox images;
9 private JLabel label; 1.1 Initialization
10 private String names[] =
11 { "bug1.gif", "bug2.gif", 1.2 Constructor
12 "travelbug.gif", "buganim.gif" };
13 private Icon icons[] =
14 { new ImageIcon( names[ 0 ] ), 1.3 Initialize JComboBox
15 new ImageIcon( names[ 1 ] ),
16 new ImageIcon( names[ 2 ] ),
17 new ImageIcon( names[ 3 ] ) };
1.4 Register
18 ItemListener
19 public ComboBoxTest()
20 {
21 super( "Testing JComboBox" );
22
23 Container c = getContentPane();
24 c.setLayout( new FlowLayout() );
25
26 images = new JComboBox( names );
27 images.setMaximumRowCount( 3 );
28
29 images.addItemListener(
30 new ItemListener() {
31 public void itemStateChanged( ItemEvent e )
32 {
33 label.setIcon(
34 icons[ images.getSelectedIndex() ] );
35 }
36 } 1.5 Event handler
37 );
38
39 c.add( images ); 2. main
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 }
Program Output
29.10 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
– MouseListener and MouseMotionListener
methods called automatically (if component is registered)
• addMouseListener
• addMouseMotionListener
29.10 Mouse Event Handling (II)
• 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
29.11.1 FlowLayout
Program Output
29.11.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
29.11.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
• myLayout.add( component, position )
• component - component to add
• position - BorderLayout.NORTH
– SOUTH, EAST, WEST, CENTER similar
– setVisible( boolean ) ( in class Jbutton)
• If false, hides component
– layoutContainer( container ) - updates
container, as before
1 // Fig. 29.18: BorderLayoutDemo.java
2 // Demonstrating BorderLayout.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 1. import
7 public class BorderLayoutDemo extends JFrame
8 implements ActionListener {
9 private JButton b[];
1.1 Declarations
10 private String names[] =
11 { "Hide North", "Hide South", "Hide East", 1.2 Initialize layout
12 "Hide West", "Hide Center" };
13 private BorderLayout layout;
14 1.3 Register event
15 public BorderLayoutDemo() handler
16 {
17 super( "BorderLayout Demo" );
18
19 layout = new BorderLayout( 5, 5 );
20
21 Container c = getContentPane();
22 c.setLayout( layout );
23
24 // instantiate button objects
25 b = new JButton[ names.length ];
26
27 for ( int i = 0; i < names.length; i++ ) {
28 b[ i ] = new JButton( names[ i ] );
29 b[ i ].addActionListener( this );
30 }
31
32 // order not important
33 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
1.4 Add components to
container
37 c.add( b[ 4 ], BorderLayout.CENTER ); // Center position
38
39 setSize( 300, 200 ); 1.5 Event handler
40 show();
41 }
42 2. main
43 public void actionPerformed( ActionEvent e )
44 {
45 for ( int i = 0; i < b.length; i++ )
46 if ( e.getSource() == b[ i ] )
47 b[ i ].setVisible( false );
48 else
49 b[ i ].setVisible( true );
50
51 // re-layout the content pane
52 layout.layoutContainer( getContentPane() );
53 }
54
55 public static void main( String args[] )
56 {
57 BorderLayoutDemo app = new BorderLayoutDemo();
58
59 app.addWindowListener(
60 new WindowAdapter() {
61 public void windowClosing( WindowEvent e )
62 {
63 System.exit( 0 );
64 }
65 }
66 );
67 }
68 }
Program Output
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
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
1 // Fig. 29.19: GridLayoutDemo.java
2 // Demonstrating GridLayout.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 1. import
7 public class GridLayoutDemo extends JFrame
8 implements ActionListener {
9 private JButton b[]; 1.1 Declarations
10 private String names[] =
11 { "one", "two", "three", "four", "five", "six" };
1.2 Initialize layout
12 private boolean toggle = true;
13 private Container c;
14 private GridLayout grid1, grid2; 1.3 Register event
15
handler
16 public GridLayoutDemo()
17 {
18 super( "GridLayout Demo" );
19
20 grid1 = new GridLayout( 2, 3, 5, 5 );
21 grid2 = new GridLayout( 3, 2 );
22
23 c = getContentPane();
24 c.setLayout( grid1 );
25
26 // create and add buttons
27 b = new JButton[ names.length ];
28
29 for (int i = 0; i < names.length; i++ ) {
30 b[ i ] = new JButton( names[ i ] );
31 b[ i ].addActionListener( this );
32 c.add( b[ i ] );
33 }
34
35 setSize( 300, 150 );
36 show();
37 }
1.4 Add components to
38
39 public void actionPerformed( ActionEvent e ) container
40 {
41 if ( toggle )
42 c.setLayout( grid2 );
1.5 Define event handler
43 else
44 c.setLayout( grid1 );
1.6 Update layout
45
46 toggle = !toggle;
(c.validate())
47 c.validate();
48 }
49
50 public static void main( String args[] ) 2. main
51 {
52 GridLayoutDemo app = new GridLayoutDemo();
53
54 app.addWindowListener(
55 new WindowAdapter() {
56 public void windowClosing( WindowEvent e )
57 {
58 System.exit( 0 );
59 }
60 }
61 );
62 }
63 }
Program Output
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 accommodate components as they are added
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)
1 // Fig. 29.20: PanelDemo.java
2 // Using a JPanel to help lay out components.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 1. import
7 public class PanelDemo extends JFrame {
8 private JPanel buttonPanel;
9 private JButton buttons[]; 1.1 Declarations
10
11 public PanelDemo()
12 { 1.2 Initialize
13 super( "Panel Demo" ); buttonPanel
14
15 Container c = getContentPane();
1.3 Panel uses
16 buttonPanel = new JPanel();
17 buttons = new JButton[ 5 ]; GridLayout
18
19 buttonPanel.setLayout(
1.4 Add components to
20 new GridLayout( 1, buttons.length ) );
21
panel
22 for ( int i = 0; i < buttons.length; i++ ) {
23 buttons[ i ] = new JButton( "Button " + (i + 1) ); 1.5 Add panel to content
24 buttonPanel.add( buttons[ i ] ); pane (BorderLayout.
25 } SOUTH)
26
27 c.add( buttonPanel, BorderLayout.SOUTH );
28
29 setSize( 425, 150 );
30 show();
31 }
32
33 public static void main( String args[] )
34 {
35 PanelDemo app = new PanelDemo();
36
2. main
37 app.addWindowListener(
38 new WindowAdapter() {
39 public void windowClosing( WindowEvent e )
40 {
41 System.exit( 0 );
42 }
43 }
44 );
45 }
46 }
Program Output
29.13 Creating a Self-Contained Subclass of
JPanel
• JPanel
– Can be used as a dedicated drawing area
• Receive mouse events
• Can extend to create new components
– Combining Swing GUI components and drawing can lead to
improper display
• GUI may cover drawing, or may be able to draw over GUI
components
– Solution: separate the GUI and graphics
• Create dedicated drawing areas as subclasses of JPanel
29.13 Creating a Self-Contained Subclass of
JPanel (II)
• Example
– Create a subclass of JPanel named
SelfContainedPanel that listens for its own mouse
events
• Draws an oval on itself (overrides paintComponent)
– Import SelfContainedPanel into another class
• The other class contains its own mouse handlers
– Add an instance of SelfContainedPanel to the content
pane
1 // Fig. 29.21: SelfContainedPanelTest.java
2 // Creating a self-contained subclass of JPanel
3 // that processes its own mouse events.
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*; 1. import
7 import com.deitel.chtp3.ch29.SelfContainedPanel;
SelfContainedPanel
8
9 public class SelfContainedPanelTest extends JFrame {
10 private SelfContainedPanel myPanel; 1.1 Create object
11
12 public SelfContainedPanelTest()
13 {
1.2 Add to content pane
14 myPanel = new SelfContainedPanel();
15 myPanel.setBackground( Color.yellow ); 1.3 Mouse event handler
16
17 Container c = getContentPane();
for application window
18 c.setLayout( new FlowLayout() );
19 c.add( myPanel );
20
21 addMouseMotionListener(
22 new MouseMotionListener() {
23 public void mouseDragged( FMouseEvent e )
24 {
25 setTitle( "Dragging: x=" + e.getX() +
26 "; y=" + e.getY() );
27 }
28
29 public void mouseMoved( MouseEvent e )
30 {
31 setTitle( "Moving: x=" + e.getX() +
32 "; y=" + e.getY() );
33 }
34 }
35 );
36 1.3 Mouse event handler
37 setSize( 300, 200 ); for application window
38 show();
39 }
40 2. main
41 public static void main( String args[] )
42 {
43 SelfContainedPanelTest app =
44 new SelfContainedPanelTest();
45
46 app.addWindowListener(
47 new WindowAdapter() {
48 public void windowClosing( WindowEvent e )
49 {
50 System.exit( 0 );
51 }
52 }
53 );
54 }
55 }
56 // Fig. 29.21: SelfContainedPanel.java
57 // A self-contained JPanel class that
58 // handles its own mouse events.
59 package com.deitel.chtp3.ch29;
60
61 import java.awt.*; Class
62 import java.awt.event.*; SelfContainedPanel
63 import javax.swing.*;
64
65 public class SelfContainedPanel extends JPanel { 1. extends JPanel
66 private int x1, y1, x2, y2;
67
1.1 Mouse event handler
68 public SelfContainedPanel()
69 {
70 addMouseListener(
71 new MouseAdapter() {
72 public void mousePressed( MouseEvent e )
73 {
74 x1 = e.getX();
75 y1 = e.getY();
76 }
77
78 public void mouseReleased( MouseEvent e )
79 {
80 x2 = e.getX();
81 y2 = e.getY();
82 repaint();
83 }
84 }
85 );
86
87 addMouseMotionListener(
88 new MouseMotionAdapter() {
89 public void mouseDragged( MouseEvent e )
90 {
91 x2 = e.getX(); 1.1 Mouse event handler
92 y2 = e.getY();
93 repaint();
94 } 2. Override
95 } paintComponent
96 );
97 }
98
99 public Dimension getPreferredSize()
100 {
101 return new Dimension( 150, 100 );
102 }
103
104 public void paintComponent( Graphics g )
105 {
106 super.paintComponent( g );
107
108 g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ),
109 Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) );
110 }
111 }
Program Output
29.14 Windows
• JFrame
– Inherits from java.awt.Frame, which inherits from
java.awt.Window
– JFrame is a window with a title bar and a border
• Not a lightweight component - not written completely in Java
• Window part of local platform's GUI components
– Different for Windows, Macintosh, and UNIX
• JFrame operations when user closes window
– Controlled with method setDefaultCloseOperation
• Interface WindowConstants (javax.swing) has three
constants to use
• DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE,
HIDE_ON_CLOSE (default)
29.14 Windows (II)
• Menus
– Important part of GUIs
– Perform actions without cluttering GUI
– Attached to objects of classes that have method
setJMenuBar
• JFrame and JApplet
• Classes used to define menus
– JMenuBar - container for menus, manages menu bar
– JMenuItem - manages menu items
• Menu items - GUI components inside a menu
• Can initiate an action or be a submenu
29.15 Using Menus with Frames (II)
• Mnemonics
– Provide quick access to menu items (File)
• Can be used with classes that have subclass
javax.swing.AbstractButton
– Use method setMnemonic
JMenu fileMenu = new JMenu( "File" )
fileMenu.setMnemonic( 'F' );
• Press Alt + F to access menu
• Methods
– setSelected( true )
• Of class AbstractButton
• Sets button/item to selected state
29.15 Using Menus with Frames (IV)
• Methods (continued)
– addSeparator()
• Class JMenu
• Inserts separator line into menu
• Dialog boxes
– Modal - No other window can be accessed while it is open
(default)
• Modeless - other windows can be accessed
– JOptionPane.showMessageDialog( parentWindow,
String, title, messageType )
– parentWindow - determines where dialog box appears
• null - displayed at center of screen
• window specified - dialog box centered horizontally over parent
29.15 Using Menus with Frames (V)
• Using menus
– Create menu bar
• Set menu bar for JFrame ( setJMenuBar( myBar ); )
– Create menus
• Set Mnemonics
– Create menu items
• Set Mnemonics
• Set event handlers
– If using JRadioButtonMenuItems
• Create a group: myGroup = new ButtonGroup();
• Add JRadioButtonMenuItems to the group
29.15 Using Menus with Frames (VI)