GUI Applications with Swing
How to create a GUI design using Java
No Java tutorial is complete without a section on GUI design using Java. The Java Foundation Classes (JFC) contain a group of features that allow developers to build graphical user interfaces (GUIs) and add rich graphics functionality and interactivity to Java applications. The Swing toolkit comes with SE and offers a set of components such as table controls, list controls, tree controls, buttons, and labels that allow users to design and implement a GUI-based tool. Further, Swing applications may be custom-fit to the look and feel of systems running different OS. Swing applications may be easily deployed over the Internet via object or applet tags embedded in an HTML file. Swing is also used to design heavy weight (complex, extensive) stand alone GUIs that deal with enterprise level data and operations.
The Swing package contains several classes that model components found in a typical Graphical User Interface (GUI). All the components are subclasses of the JComponent class. Component classes include the JApplet, JFrame, Jpanel, and JDialog classes that serve as the base of any Swing application. An instance of a JFrame or JApplet with one or more JPanels is created and other components are appropriately positioned on these base components. The developer may choose to place a few JMenu Components on the top bar (JMenu may be used to place pull down menus like the ubiquitous 'File' and 'Edit' menus on the top bar of conventional applications), a couple of JButton components (JButton may be clicked on to perform specific actions) and so on. Swing contains an exhaustive collection of such GUI related components that make GUI creation very easy.
Some GUI Components from javax.swing
|
JApplet |
An extended version of java.applet.Applet that adds support for the JFC/Swing component architecture |
|
JButton |
An implementation of a "push" button |
|
JCheckBox |
An implementation of a check box. An item that can be selected or deselected, and which displays its state to the user. By convention, any number of check boxes in a group can be selected |
|
JColorChooser |
Provides a pane of controls designed to allow a user to manipulate and select a color |
|
JComboBox |
A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value |
|
JDialog |
The main class for creating a dialog window |
|
JFileChooser |
Provides a simple mechanism for the user to choose a file |
|
JLabel |
A display area for a short text string or an image, or both |
|
JList |
A component that allows the user to select one or more objects from a list. A separate model, ListModel, represents the contents of the list |
|
JMenu |
An implementation of a menu - a popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar. In addition to JMenuItems, a JMenu can also contain JSeparators |
|
JMenuBar |
An implementation of a menu bar. You add JMenu objects to the menu bar to construct a menu. When the user selects a JMenu object, its associated JPopupMenu is displayed, allowing the user to select one of the JMenuItems on it |
|
JPasswordField |
PasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters |
|
JRadioButton |
An implementation of a radio button -- an item that can be selected or deselected, and which displays its state to the user |
|
JSlider |
A component that lets the user graphically select a value by sliding a knob within a bounded interval |
|
JTable |
Used to display and edit regular two-dimensional tables of cells |
|
JTextArea |
JTextArea is a multi-line area that displays plain text |
|
JTextField |
JTextField is a lightweight component that allows the editing of a single line of text |
Components may be customized to fit the look and feel of different operating systems in the newer versions of Java. We will go over the basics of the swing package in this chapter. The following is an example of a code that will create a basic Swing Application that consists of a single button
import java.lang.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class myGUI {
public static void main(String args[]) {
// Create the main frame that will hold the GUI
JFrame myFrame = new JFrame();
// Create panel with a flowing layout
// Flow panels automatically position elements around
// each other
JPanel myPanel = new JPanel(new FlowLayout());
//Create a button
JButton myButton = new JButton("Click!");
// Place button on the panel
myPanel.add(myButton);
// Set panel as content for frame
myFrame.setContentPane(myPanel);
// Quit Application when Frame window is closed
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Original location of application window
myFrame.setLocation(100, 100);
//Load frame and make it visible
myFrame.pack();
myFrame.setVisible(true);
}
}
Create a new Java Class called 'myGUI' using the File -> New File menu item in the Netbeans5.5 MySamples project. Replace all the code in the new file with the above code. Save the file, compile it and run it using Build -> Compile "myGUI.java" and Run -> Run File -> myGUI.java. Your output should look like this:
Screenshot 6a: A simple Swing Application
Event handlers are used to add functionality to swing components. A listener object waits for the appropriate event (mouse click, keyboard press and so on). Once the event happens, the listener is triggered and the method that handles the event is automatically invoked. The following code demonstrates adding functionality through an action listener. The new modified code is in red:
class myGUI {
static JFrame myFrame = null;
static JButton myButton = null;
public static void main(String args[]) {
// Create the main frame that will hold the GUI
myFrame = new JFrame();
// Create panel with a flowing layout
// Flow panels automatically position elements around
// each other
JPanel myPanel = new JPanel(new FlowLayout());
//Create button
myButton = new JButton("Click!");
// Add an action listener.
myButton.addActionListener(new ButtonListener());
.
.
(Other code in the Main method is unchanged)
.
.
}
// Event Handler
static class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (myButton.getText() == "Click!") {
myButton.setText("Got A Click!");
}
else {
myButton.setText("Click!");
}
}
}
}
Note that we have added an inner class for the event handler. An action listener for the button with the new inner class as a parameter was also added. Whenever myButton is clicked, the actionPerformed method within the buttonListener inner class is automatically invoked. Here, the text in the button is toggled between 'Click!' and 'Got a Click'. Modify myGUI.java to reflect the above changes, and then compile and run it. When you click on the button, the text in the button will change to 'Got a Click!'. Another click will revert the text to 'Click!'. Swing Applications use components and action listeners together to provide functionality.
The button and frame objects are declared as fields of the myGUI class rather than within the main method. This is required because the inner ButtonListener class will not be able to access a local variable of the main method. Also, the inner ButtonListener class, myFrame, and myButton are declared static. For consistency, Non-static variables and methods cannot be referenced in the main method which is itself static. All variables declared within a static method are also static. Since a static method is invoked through the class itself, rather than in an instance, it makes no sense to refer to instance variables and methods in a static method.
In the next chapter, we will combine and integrate concurrency concepts with GUI concepts to devise a simple, thread safe Swing application that will display a slide show of the fruits in the myFruits ArrayList.