HTML Markup | JavaScript | Java | Home & Links

Tutorial 10 - Intermediate Swing

This tutorial explores freeform and restricted entry Swing components. Basics|Advanced

Text Entry

Text fields for input or output of single lines are created using the JTextField class. JPassWordField is similar to JTextField but displays typed characters as asterisks for security.

Text areas for blocks or multiple lines of text are created using the JTextArea (simple text), JEditorPane (html, rtf and other formatted text) or JTextPane classes. Methods include getText(), setText(), append(str), insert(str,pos), replace(str,beg,end), setEditable(bool), setLineWrap(bool) and setWrapStyleWord(bool). Text areas are often contained within JScrollPane containers to allow scrolling of the display area. WSFiler demos a handy class for moving text area data to/from files.

Formatted text fields allow display in a locale specific manner as well as restricting entry to valid characters. The class constructor used is JFormattedTextField(). Formats include: Date, Integer, Float, currency, percent and URI. Invalid input will be rejected. Up/down arrows cause some format data to alter by one. The escape key is used for canceling entries. SimpleFTF demos how formatted text fields are set up and used.

Dialog Boxes

Dialogs are short messages, confirmations or input prompts for simple string information which appear as popup windows. Dialogs can either be modal (must be ended before another window is accessed) or modeless.

JOptionPane provides a modal dialog with predefined methods for each type of prompt. Each JOptionPane method has a first parameter that points to a parent (ie. window that it appears in) or null (default to the current window). The second parameter is the message or prompt to be displayed.

showMessageDialog() has two optional parameters to set a dialog title and to select the dialog's icon. The dialog has a single 'ok' button for completion and no data is returned by this method.

JOptionPane.showMessageDialog(null,"This is just a message",
    "Message Dialog",JOptionPane.PLAIN_MESSAGE);

showConfirmDialog() has three optional parameters to set a dialog title, alter the button display, and select the dialogs icon. By default there are three buttons 'Yes', 'No' and 'Cancel' for dialog completion. The returned value is one of JOptionPane.YES_OPTION, JOptionPane.NO_OPTION or JOptionPane.CANCEL_OPTION.

pressed=JOptionPane.showConfirmBox(null,"Everything ok");
if (pressed==JOptionPane.YES_OPTION) {/* do action for confirmed */}

showInputDialog() has two optional parameters to set a dialog title and to select the dialog's icon. There is both an 'ok' button and a 'cancel' button for dialog completion. Information typed into the entry box is returned as a string.

user_data=JOptionPane.showInputDialog(null,"What's your name");

The list of icon types that can be displayed (by predefined constant) contains ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE and WARNING_MESSAGE.

JDialog provides a simple unadorned window used to create customized dialog boxes. Customization can include modality and mnemonics (aka hotkeys).


Buttons are often used to let the user start a process. They are created with the JButton() constructor and. Buttons can be deactivated with the setEnabled(false) method and tested with the isEnabled() method. setMnemonic(char) allows a hot key to be associated with the button. Buttons use an ActionEvent event listener that reacts to a button press. Many GUIs use an array set of buttons. Check Bgui for a demo of this technique.

Toggle buttons are a visual push on - push off mechanism. They are created with the JToggleButton() constructor. The isSelected() method returns the state of the button. In addition to ActionEvent, ChangeEvent and ItemEvent are triggered.


Checkboxes allow restricted selection of options. More than one option (or none) may be selected. JCheckBox() is used to construct these widgets. A checkbox widget is normally associated with a JLabel caption but can also be created by using a constructor with a caption parameter. The getSelectedObjects() method checks the state of a checkbox.

Often there is no need for checkbox events as their states are checked when a process button is selected. But there are times you may wish to update dynamically as an checkbox item is changed. This requires a different interface called ItemListener which responds to change of state rather than mouse clicks. The required implementation method is itemStateChanged(). A simple two checkbox example follows:

NOTE: Layout managers are explained in a following tutorial.

Radio Buttons

Radio buttons allow restricted selection of alternatives. Only one radio button may be selected at a time. JRadioButton is used to construct these widgets. A radio button is normally associated with a JLabel caption but can also be created using a constructor with a caption parameter. The isSelected() method checks the state of a radio button.

Button groups are used to ensure the mutual exclusivity of buttons in the group (ie. only one can be on at a time). Use ButtonGroup() to construct a button group and then add buttons with the add() method.

Borders are normally added to button groups for a visual separation. Unfortunately this doesn't work in Java! You must create a pane for the group and then add a border to the pane. For example:

NOTE: Layout managers are explained in a following tutorial.

3rd Party Widgets

Although the Java SDK provides many commonly used IO widgets, some applications such as instrumentation require highly specialized widgets. JKnob shows how to write a new io widget and then add it to an application. JFreeChart and JCalendar are two popular widgets. Google third party swing widgets for more stuff.

Tutorial Source Code

Obtain source for JKnob, SimpleFTF, WSFiler here.

JR's HomePage | Comments [jatutora.htm:2016 02 09]