About the Author:

9.1 Developing with Swing

Developing with Swing

A Basic Swing Example

To write a simple Swing application we do not have to make too many changes to a standard AWT application. Figure 9.3, “A Simple Swing Application” shows a simple Swing button application, that should provide you with a template for writing your own applications.

You will notice that this application does not shutdown correctly when the x button is pressed on the top left side of the application - it will simply make the window disappear. This is because we have not written the code to handle this. You can shutdown the application by typing "CTRL-C" in the DOS shell window or press the square stop button within Eclipse

Some points about this application:

It is a full application, so it extends the JFrame class, the Swing version of Frame (java.awt.Frame) class.

Themain()method creates an object of theSimpleSwingApplicationby callingnew SimpleSwingApplication();, which creates an anonymous object.

this.getContentPane() returns the Container object for this JFrame. You cannot add components to the JFrame directly - you must use the getContentPane() method call.

this.pack() sets the JFrame object to its components preferred sizes. this.setVisible(true) makes the JFrame object visible on the screen. You usually make this call last as all layout has been carried out and the frame will not be changing sizes and moving after it is displayed. You can also have refresh problems if you do not do this last.

Example Extra Swing Features

As previously discussed, Swing brings a huge range of components to the Java programming language. Many of the components we discussed previously remain much the same. So for example:

The JButton class replaces the java.awt.Button AWT class and has much the same functionality, with minor differences. For example we can add an image icon to the button surface using the following code:

URLiconLocation=this.getClass().getResource("image.gif");

System.out.println("Icon is at: "+iconLocation);

ImageIconicon=newImageIcon(iconLocation,"A running dog icon");

this.status=newJTextField(20);

this.button1=newJButton("Button 1",icon);

this.button2=newJButton("Button 2",icon);

Where theImage1 is a regular Image object and the ImageIcon takes an Image object as a constructor parameter to allow of the creation of a component based image display, i.e. one that could be added to a layout or any container etc. Once we have created this ImageIcon object we can pass this to the constructor of JButton to create a button with an image display. This can be seen as in Figure 9.4, “A Swing Image Button Example”. The source code for this example is here -SwingImageButton.java

Figure 9.4. A Swing Image Button Example

If there is no text on a button, i.e. if it was just an image button then there would be no action command (by default) to compare to. It is better in this application to compare to the source of the event, i.e. the object reference. You can change the code in theactionPerformed()method frome.getActionCommand()toe.getSource(). Alternatively, you could attach an action command to the JButton.

Core Swing Components

Figure 9.5, “The Swing Component Hierarchy” displays a sample of the Swing Component Hierarchy. This is only a subset of the Swing components that are available for use. You can see in this figure that JApplet, JFrame, JDialog and JComponent are replacements for their equivalent AWT components. JFrame is actually a heavyweight component, it will have a different appearance depending on the Operating System it is running on.

Figure 9.5. The Swing Component Hierarchy

The Swing equivalent components for the AWT components that we have discussed previously are:

JButton - as discussed replaces the AWT Button and has a few changes. For one as in Figure 9.5, “The Swing Component Hierarchy” the parent class is AbstractButton which defines a common behaviour for all buttons, for example there is a two-state JToggleButton class also inheriting from AbstractButton. Button objects can also have an image icon added to the button area.

JTextField - replaces the TextField class and remains essentially the same. There is a slight difference in the event structure and we have the added benefit of some derived sub-classes, such as JPasswordField which allows a password to be entered using a character mask, and JFormattedTextField to allow for the entry of formatted text, such as a date of birth.

JTextArea - replaces the TextArea class and is slightly different. For one thing, the JTextArea does not handle scrolling of the text to allow you to have more control over its functionality. To add a scrolling capability to a JTextAreacomponent you can add it to a JScrollPane component. By default, the line wrapping property is set to false. You can enable line wrapping by using the setWrapStyleWord() method that requires a Boolean value, where true means wrap at word boundaries and false means wrap at character boundaries (could be mid-word).

JPanel - replaces the Panel class and remains much the same

JRadioButton - replaces the RadioButton component and has the added facility of adding an ImageIcon to it. Again you use this with a ButtonGroup object to create a group of buttons where only one may be selected at a time.

JCheckBox - replaces the CheckBox component. It is actually a child of the AbstractButton class (as is JButton). As such, you can add an ImageIcon object. Other operation remains the same.

JComboBox - is the Swing implementation of ComboBox, a combination of a text field and drop-down list that lets the user either type in a value or select it from a list that is displayed when the user asks for it. The editing capability can also be disabled so that the JComboBox acts only as a drop down list.

JList - is the replacement for List. Similarly to the JTextArea you have to add the component to a JScrollPane to enable scrolling on this component. The items in the list can be changed dynamically at run-time and the component has a special listener swing.event.ListDataListener.

Exercise - Swing Components

The JTextArea component in the center should have the ability to scroll (with Scrollbars always visible).

See the Figure 9.6, “A Swing Exercise for You!”TextArea for more information.

Figure 9.6. A Swing Exercise for You!

Hint: Remember to use the API documentation for method calls etc. You will probably have to use the setForeground(Color c) method to change the text colour of the TextArea, unless you can work out a better way.

Solution: My solution is here, but please don't look at it until you have had a good attempt at it - SwingExercise.java

Other Properties added to Swing Components

ToolTips can be added to components to allow a further description of the functionality of the component. You can use the setToolTipText() method of the JComponent class. When you float over the JButton object the ToolTip will appear as in Figure 9.7, “An Example of Swing ToolTips”. You can see the source code in SwingTooltips.java

Swing also provides borders for JComponent components. Border is an interface that has many default implementations that you can use, or even create your own. Figure 9.8, “An Example of Swing Borders” shows three different border types that you can use. The JTextField component is surrounded by a EmptyBorder with a colour of white, the first JButton component is surrounded by a blue MatteBorder and the last JButton component is surrounded by a LineBorder with a line width of 10 pixels, a color of green and rounded corners set to true. You must import the javax.swing.border.* package to use these pre-defined borders. The code used for the example shown in Figure 9.8, “An Example of Swing Borders” is as below