HTML Markup | JavaScript | Java | Home & Links

Tutorial 10 - Swing GUI Widgets

A Graphical User Interface (GUI) is a visual paradigm which allows a user to communicate with a program in an intuitive way. Its main features are widgets (aka controls) and event driven activities. Application users expect a graphical interface. The next few tutorials will introduce Java's GUI widgets as well as some layout design considerations. One reference with lots of examples can be found in the Guidebook. Swing Sightings demos Swing in significant applications.

Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing. AWT uses the native operating system's window routines so the visual effect is dependent on the run-time system platform. But this is contrary to the concept of having a virtual model. Swing allows three modes: a unified look and feel [the default], the native platform look, or a specific platform's look. Swing is built on the original objects and framework of AWT. Swing components have the prefix J to distinguish them from the original AWT ones (eg JFrame instead of Frame). To include Swing components and methods in your project you must import the java.awt.*, java.awt.event.*, and javax.swing.* packages. Intermediate|Advanced

Containers, Windows and Content Panes

Containers are components that are used to hold and group widgets such as text fields and checkboxes and other components. Methods common to many containers include: add(), pack(), requestFocus() and setToolTipText().

Windows are top-level containers which interface to the operating system's window manager. Their types are: Primary (adorned with minimize, maximize and close buttons) [JFrame]; Secondary [JDialog]; Plain (no border - used for splash screens) [JWindow] and XHTML document [JApplet].

Content panes are intermediate containers such as JPanel, JOptionPane, JScrollPane, JLayeredPane, JSplitPane and JTabbedPane which organize the layout structure when multiple controls are being used.

JInternalFrame is an adorned lower-level frame used with MDI (Multiple Document Interface). It prevents overlapping of the documents.

JFrame and JPanel

JFrame is the most commonly used top-level container. It adds basic functionality such as minimize, maximize, close, title and border to basic frames and windows. Some important JFrame methods are: getTitle(), setBounds(x,y,w,h), setLocation(x,y), setMaximumSize(w,h), setMinimumSize(w,h), setPreferredSize(w,h), setResizable(bool), setSize(w,h) and setTitle(str). setVisible(bool) replaces the deprecated show() method. The setDefaultCloseOperation(constant) method controls the close icon action. The constant normally is EXIT_ON_CLOSE.

JPanel is the most commonly used content pane. An instance of the pane is created and then added to a frame. The add(widgetName) method allows widgets (ie GUI controls) to be added to the pane. The way they are added is controlled by the current layout manager. JPanel defaults to FlowLayout. All other content panes default to BorderLayout.

The following is a simple template that creates a JFrame container class using inheritance. The created subclass then adds a JPanel. This custom class will form the basis of many of our GUI examples.

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 dismissed before another window is accessed) or modeless.

JOptionPane provides a modal dialog with predefined methods for each type of dialog. 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. New instances of JOptionPane are not normally generated.

showMessageDialog() has two more 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 more 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 aok");
if (pressed==JOptionPane.YES_OPTION)
   {
   // do the action for confirmation
   }

showInputDialog() has two more 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. Any 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).

Labels, Icons and Buttons

Labels are non-interactive text objects most commonly used as prompts. They are created using the JLabel() constructor with the required text as the first parameter. Another parameter can be added using a SwingConstant value to set horizontal alignment. Vertical alignment is through the setVerticalAlignment() method. The contents of a label can be changed with the setText() method.

Icons can be easily added to labels or other controls either to brand, dress up, or aid accessibility. Icons are constructed from the ImageIcon class and then added as a parameter to the label (or other) control. An extra parameter can be used to control the position of the text relative to the icon. It must use one of the SwingConstants values.

ImageIcon icon=new ImageIcon("smile.gif");
JLabel label=new JLabel("hello",icon,SwingConstants.RIGHT);
pane.add(label);

Buttons are created with the JButton() constructor and are used to start operations. They can be deactivated with the setEnabled(false) method and tested with the isEnabled() method. A useful method is setMnemonic(char) which allows a hot key to be associated with the button. Simple buttons require an ActionEvent event listener that reacts to the button click. 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, the ChangeEvent is triggered.

Basic Event Listeners

GUIs are event-based as they respond to user actions such as buttons, keyboard input and mouse activities. Java uses event listeners to monitor activity on specified objects and react to specific conditions. Check the appendix for a listing of event listeners. View advanced event listeners for techniques on organizing many different events in larger projects.

The first step in adding a basic button push event handler to the above example is to import awt.event.* which contains all of the event classes. Next add the phrase implements ActionListener to the class header to use the interface. Register event listeners for each button widget using the addActionListener(this) method. The reserved word this indicates that the required (by implements ActionListener) handler method called actionPerformed() will be included in the current class. For example:

Bounded-Range Components

Bounded-range components are controls that have a single integer value within fixed integer boundaries. Examples of bounded-range controls are progress bars. sliders and scroll bars. Each bounded-range component has the following methods: setExtent(), setMaximum(), setMinimum(), setValue(), getValueIsAdjusting() and setOrientation(). Bounded-range components use ChangeEvent to start an update.

Progress bars indicate status for time consuming jobs. The basic JProgressBar class offers a subtle control. If you want a dialog frame for canceling an operation the classes, ProgressMonitor and ProgressMonitorInputStream are better choices. ProgressMonitorInputStream is a stream filter in addition to a progress monitor. ProgBar.java is a simple progress bar demo.

Sliders allow integer selection within limits. They can be dressed up with ticks and labels using setPaintTicks(true) and setPaintLabels(true). setMajorTickSpacing(int) and setMinorTickSpacing(int) set the intervals used for marker ticks. setSnapToTicks(true) forces the slider to the closest tick. setInverted(true) reverses the low and high marks. labelTable is a dictionary of slider values and Jlabel objects for painting the object. Slider.java is a simple slider demo.



JR's HomePage | Comments [jatutora.htm:2011 12 07]