Basic Graphical User Interface Components
A graphical user interface (GUI) presents a pictorial interface to a program, GUI's allow the user to work in a more productive manner.
A GUI component is an object with which the user interacts via the mouse or keyboard, below are some of the Java GUI components
Some of the basic GUI components are
JLabel | An area where uneditable text or icons can be displayed |
JTextField | An area where the user inputs data from the keyboard, this area can also display data |
JButton | An area that triggers an event when clicked |
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 typing into the box |
JList | An area where a list of items is displayed from which the user can make a selection by clicking once on any element in the list. Double-clicking an element in the list generates an action event, Multiple elements can be selected |
JPanel | A container in which components can be placed |
Swing Overview
There are two classes that create the GUI components
swing class |
These are the newest components and are written, manipulated and displayed completely in Java. These components are commonly referred to as lightweight components because being written in Java they are not weighed down by the complex GUI capabilities of the platform on which they are used. |
awt class (abstract windowing toolkit) |
These components are directly tied to the local platform's graphical user interface capabilities. These components are commonly referred to as heavyweight components they rely on the local platforms window system to determine their functionality and their look and feel. These components are less flexible than the swing components. Each heavyweight component has a peer that is responsible for the interactions between the component and the local platform to display and manipulate the component. |
The below diagram shows the swing and awt hierarachy
Labels provide text instructions or information on a GUI.
JLabel Example | import javax.swing.*; import java.awt.*; import java.awt.event.*; public class LabelTest extends JFrame { private JLabel label1, label2, label3; public LabelTest() { super( "Testing JLabel" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); c.add( label1 ); // JLabel constructor with string, Icon and // alignment arguments Icon bug = new ImageIcon( "bug1.gif" ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); label2.setToolTipText( "This is label2" ); c.add( label2 ); // JLabel constructor no arguments 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" ); c.add( label3 ); setSize( 275, 170 ); show(); } public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } Note: the image can be obtain from here |
GUI's are event driven, you interact with the GUI by moving the mouse, clicking the mouse or via the keyboard. When these events occur they are passed to the program, code will handle the event depending on what you want to happen. To process a graphical user interface event, the programmer must perform two key tasks, register an event listener and implement an event handler.
The below diagram shows the awt event hierarchy
An event listener listens for a type of event, this then invokes the event handler to perform some action. We will use the event handling in some of the example below
These are single-line areas in which text can be entered by the user from the keyboard or text can simply be displayed, JPasswordField hides the typed characters for security. When the user hit enters after typing an action event occurs, if an event listener is registered the event will be processed and the data in the fields can be used in the program.
JTextField and JPasswordField example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextFieldTest extends JFrame { private JTextField text1, text2, text3; private JPasswordField password; public TextFieldTest() { super( "Testing JTextField and JPasswordField" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); // construct textfield with default sizing text1 = new JTextField( 10 ); c.add( text1 ); // construct textfield with default text text2 = new JTextField( "Enter text here" ); c.add( text2 ); // construct textfield with default text and // 20 visible elements and no event handler text3 = new JTextField( "Uneditable text field", 20 ); text3.setEditable( false ); c.add( text3 ); // construct textfield with default text password = new JPasswordField( "Hidden text" ); c.add( password ); TextFieldHandler handler = new TextFieldHandler(); text1.addActionListener( handler ); text2.addActionListener( handler ); text3.addActionListener( handler ); password.addActionListener( handler ); setSize( 325, 100 ); show(); } public static void main( String args[] ) { TextFieldTest app = new TextFieldTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } // inner class for event handling private class TextFieldHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { String s = ""; if ( e.getSource() == text1 ) s = "text1: " + e.getActionCommand(); else if ( e.getSource() == text2 ) s = "text2: " + e.getActionCommand(); else if ( e.getSource() == text3 ) s = "text3: " + e.getActionCommand(); else if ( e.getSource() == password ) { JPasswordField pwd = (JPasswordField) e.getSource(); s = "password: " + new String( pwd.getPassword() ); } JOptionPane.showMessageDialog( null, s ); } } } |
A button is a component the user clicks to trigger a specific action. There are several types of buttons
JButton Example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; public ButtonTest() { super( "Testing Buttons" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); // create buttons plainButton = new JButton( "Plain Button" ); c.add( plainButton ); Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); c.add( fancyButton ); // create an instance of inner class ButtonHandler // to use for button event handling ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); setSize( 275, 100 ); show(); } public static void main( String args[] ) { ButtonTest app = new ButtonTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } // inner class for button event handling private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { JOptionPane.showMessageDialog( null, "You pressed: " + e.getActionCommand() ); } } } Note: the images are located here and here |
The swing GUI components contain three types of state buttons, JToggleButton, JCheckBox and JRadioButton, they all have on/off or true/false values.
JCheckBox example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxTest extends JFrame { private JTextField t; private JCheckBox bold, italic; public CheckBoxTest() { super( "JCheckBox Test" ); Container c = getContentPane(); c.setLayout(new FlowLayout()); t = new JTextField( "Watch the font style change", 20 ); t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) ); c.add( t ); // create checkbox objects bold = new JCheckBox( "Bold" ); c.add( bold ); italic = new JCheckBox( "Italic" ); c.add( italic ); CheckBoxHandler handler = new CheckBoxHandler(); bold.addItemListener( handler ); italic.addItemListener( handler ); setSize( 275, 100 ); show(); } public static void main( String args[] ) { CheckBoxTest app = new CheckBoxTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN; public void itemStateChanged( ItemEvent e ) { if ( e.getSource() == bold ) if ( e.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; if ( e.getSource() == italic ) if ( e.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN; t.setFont( new Font( "TimesRoman", valBold + valItalic, 14 ) ); t.repaint(); } } } |
JRadioButton example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonTest extends JFrame { private JTextField t; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plain, bold, italic, boldItalic; private ButtonGroup radioGroup; public RadioButtonTest() { super( "RadioButton Test" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); t = new JTextField( "Watch the font style change", 25 ); c.add( t ); // Create radio buttons plain = new JRadioButton( "Plain", true ); c.add( plain ); bold = new JRadioButton( "Bold", false); c.add( bold ); italic = new JRadioButton( "Italic", false ); c.add( italic ); boldItalic = new JRadioButton( "Bold/Italic", false ); c.add( boldItalic ); // register events RadioButtonHandler handler = new RadioButtonHandler(); plain.addItemListener( handler ); bold.addItemListener( handler ); italic.addItemListener( handler ); boldItalic.addItemListener( handler ); // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); radioGroup.add( plain ); radioGroup.add( bold ); radioGroup.add( italic ); radioGroup.add( boldItalic ); plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); boldItalicFont = new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); t.setFont( plainFont ); setSize( 300, 100 ); show(); } public static void main( String args[] ) { RadioButtonTest app = new RadioButtonTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } private class RadioButtonHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) { if ( e.getSource() == plain ) t.setFont( plainFont ); else if ( e.getSource() == bold ) t.setFont( boldFont ); else if ( e.getSource() == italic ) t.setFont( italicFont ); else if ( e.getSource() == boldItalic ) t.setFont( boldItalicFont ); t.repaint(); } } } |
A combo box (sometimes called a drop-down list) provides a list of items from which the user can make a selection.
JComboBox example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxTest extends JFrame { private JComboBox images; private JLabel label; private String names[] = { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; private Icon icons[] = { new ImageIcon( names[ 0 ] ), new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ), new ImageIcon( names[ 3 ] ) }; public ComboBoxTest() { super( "Testing JComboBox" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); images = new JComboBox( names ); images.setMaximumRowCount( 3 ); images.addItemListener( new ItemListener() { public void itemStateChanged( ItemEvent e ) { label.setIcon( icons[ images.getSelectedIndex() ] ); } } ); c.add( images ); label = new JLabel( icons[ 0 ] ); c.add( label ); setSize( 350, 100 ); show(); } public static void main( String args[] ) { ComboBoxTest app = new ComboBoxTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } Note: the images are located here, here, here and here |
A list displays a set of items from which the user man select one or more items.
JList example | import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class ListTest extends JFrame { private JList colorList; private Container c; private String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; private Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow }; public ListTest() { super( "List Test" ); c = getContentPane(); c.setLayout( new FlowLayout() ); // create a list with the items in the colorNames array colorList = new JList( colorNames ); colorList.setVisibleRowCount( 5 ); // do not allow multiple selections colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); // add a JScrollPane containing the JList // to the content pane c.add( new JScrollPane( colorList ) ); // set up event handler colorList.addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent e ) { c.setBackground( colors[ colorList.getSelectedIndex() ] ); } } ); setSize( 350, 150 ); show(); } public static void main( String args[] ) { ListTest app = new ListTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } |
A multiple-selection list enables the user to select many items from a JList.
Multiple-Seecltion List example | import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MultipleSelection extends JFrame { private JList colorList, copyList; private JButton copy; private String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; public MultipleSelection() { super( "Multiple Selection Lists" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); colorList = new JList( colorNames ); colorList.setVisibleRowCount( 5 ); colorList.setFixedCellHeight( 15 ); colorList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); c.add( new JScrollPane( colorList ) ); // create copy button copy = new JButton( "Copy >>>" ); copy.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { // place selected values in copyList copyList.setListData( colorList.getSelectedValues() ); } } ); c.add( copy ); copyList = new JList( ); copyList.setVisibleRowCount( 5 ); copyList.setFixedCellWidth( 100 ); copyList.setFixedCellHeight( 15 ); copyList.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION ); c.add( new JScrollPane( copyList ) ); setSize( 300, 120 ); show(); } public static void main( String args[] ) { MultipleSelection app = new MultipleSelection(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } |
The mouse can have two events clicking the buttons and moving the mouse. MouseListener and MouseMotionListener can handle these events and action as necessary.
There are a number of interface methods
mousePressed(MouseEvent e) | MouseListener | Called when a mouse button is pressed with the mouse cursor on a component |
mouseClicked(MouseEvent e) | MouseListener | Called when a mouse button is pressed and released without moving the mouse |
mouseReleased(MouseEvent e) | MouseListener | Called when a mouse button is released after being pressed |
mouseEntered(MouseEvent e) | MouseListener | Called when a mouse cursor enters the bounds of a component |
mouseExited(MouseEvent e) | MouseListener | Called when a mouse cursor leaves the bounds of a component |
mouseDragged(MouseEvent e) | MouseMotionListener | Called when a mouse button is pressed and the mouse is moved |
mouseMoved(MouseEvent e) | MouseMotionListener | Called when a mouse is moved with the mouse cursor on a component |
MouseListener example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; public MouseTracker() { super( "Demonstrating Mouse Events" ); statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events addMouseListener( this ); addMouseMotionListener( this ); setSize( 275, 100 ); show(); } // MouseListener event handlers public void mouseClicked( MouseEvent e ) { statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" ); } public void mousePressed( MouseEvent e ) { statusBar.setText( "Pressed at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseReleased( MouseEvent e ) { statusBar.setText( "Released at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseEntered( MouseEvent e ) { statusBar.setText( "Mouse in window" ); } public void mouseExited( MouseEvent e ) { statusBar.setText( "Mouse outside window" ); } // MouseMotionListener event handlers public void mouseDragged( MouseEvent e ) { statusBar.setText( "Dragged at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseMoved( MouseEvent e ) { statusBar.setText( "Moved at [" + e.getX() + ", " + e.getY() + "]" ); } public static void main( String args[] ) { MouseTracker app = new MouseTracker(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } |
Java packages java.awt.event and java.swing.event provide event-listener adapters classes. An adapter class implements an interface and provides default implementation of every method in the interface. The programmer can extend the adapter class to inherit the default implementation of every method then override the method needed for event handling (the default being an empty body).
You can see the adapter class in the event handling diagram above.
Adapter Example | import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Painter extends JFrame { private int xValue = -10, yValue = -10; public Painter() { super( "A simple paint program" ); getContentPane().add( new Label( "Drag the mouse to draw" ), BorderLayout.SOUTH ); // The MouseMotionAdapter Class |
The keyListener event-listener interface is used to handle key events. A class that implements KeyListener must provide definitions for methods, keyPressed, keyReleased and keyTyped, each of which receives a KeyEvent as its argument.
KeyPressed | called in repsonse to pressing a key |
KeyReleased | called when a key is released after a KeyPressed or KeyTyped action. |
KeyTyped | called in repsonse to pressing a key that is not a action key (arrow keys, home key, function keys, etc) |
Now for an example
Keyboard event example | import javax.swing.*; import java.awt.*; import java.awt.event.*; public class KeyDemo extends JFrame implements KeyListener { private String line1 = "", line2 = ""; private String line3 = ""; private JTextArea textArea; public KeyDemo() { super( "Demonstrating Keystroke Events" ); textArea = new JTextArea( 10, 15 ); textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); // allow frame to process Key events addKeyListener( this ); getContentPane().add( textArea ); setSize( 350, 100 ); show(); } public void keyPressed( KeyEvent e ) { line1 = "Key pressed: " + e.getKeyText( e.getKeyCode() ); setLines2and3( e ); } public void keyReleased( KeyEvent e ) { line1 = "Key released: " + e.getKeyText( e.getKeyCode() ); setLines2and3( e ); } public void keyTyped( KeyEvent e ) { line1 = "Key typed: " + e.getKeyChar(); setLines2and3( e ); } private void setLines2and3( KeyEvent e ) { line2 = "This key is " +( e.isActionKey() ? "" : "not " ) + "an action key"; String temp = e.getKeyModifiersText( e.getModifiers() ); line3 = "Modifier keys pressed: " + ( temp.equals( "" ) ? "none" : temp ); textArea.setText( line1 + "\n" + line2 + "\n" + line3 + "\n" ); } public static void main( String args[] ) { KeyDemo app = new KeyDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } |
Layout Managers
See Layout Managers for more details
Complex GUI's require that each component be placed in an exact location. They often consist of multiple panels with each panel's components arranged in a specific layout.
Panel example | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelDemo extends JFrame { private JPanel buttonPanel; private JButton buttons[]; public PanelDemo() { super( "Panel Demo" ); Container c = getContentPane(); buttonPanel = new JPanel(); buttons = new JButton[ 5 ]; buttonPanel.setLayout( new GridLayout( 1, buttons.length ) ); for ( int i = 0; i < buttons.length; i++ ) { buttons[ i ] = new JButton( "Button " + (i + 1) ); buttonPanel.add( buttons[ i ] ); } c.add( buttonPanel, BorderLayout.SOUTH ); setSize( 425, 150 ); show(); } public static void main( String args[] ) { PanelDemo app = new PanelDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } |