One of the easiest ways to improve the visual appeal of a GUI is to use icons, small images used to identify buttons and other parts of an interface.
With many of the components in the Swing class library, you can label a component with an image instead of text by using the ImageIcon
class in the javax.swing
package.
Although some operating systems use the character to separate folders and filenames, the
ImageIcon
constructor requires the /
character as a separator.
You can create an ImageIcon
from a file on your computer by calling the ImageIcon(
String)
constructor method. The argument to the method is either the name of the file or its location and name, as in these examples:
ImageIcon stopSign = new ImageIcon("stopsign.gif");
ImageIcon saveFile = new ImageIcon("images/savefile.gif");
The graphics file used to create the image icon must be in GIF, JPEG, or PNG format. Most are in GIF format which is well suited to displaying small graphics with a limited number of colors.
The ImageIcon
constructor loads the entire image from the file immediately.
You can use image icons as labels and buttons by using the JLabel(
ImageIcon)
and JButton(
ImageIcon)
constructor methods, as in the following example:
ImageIcon siteLogo = new ImageIcon("siteLogo.gif");
JLabel logoLabel = new JLabel(siteLogo);
ImageIcon searchWeb = new ImageIcon("searchGraphic.gif");
JButton search = new JTextField(searchWeb);
Several components can have an icon and a text label. The following statement creates a button with both:
JButton refresh = new JButton("Refresh",
"images/refreshIcon.gif");
Image icons often are used in toolbars, containers that group several components together into a row or column.
Toolbars, which are created by using the JToolBar
class, can be designed so that a user can move them from one part of a GUI to another. This process is called docking, and these components are also called dockable toolbars.
You can create a toolbar with one of the following constructor methods:
• JToolBar()
—Create a toolbar that lines up components in a horizontal direction
• JToolBar(
int)
—Create a toolbar that lines up components in the specified direction, which is either SwingConstants.HORIZONTAL
or SwingConstants.VERTICAL
.
Components are added to a toolbar in the same way they are added to other containers—the add(
Component)
method is called with the component to be added.
For a toolbar to be dockable, it must be placed in a container that uses BorderLayout
as its layout manager. This layout arranges a container into north, south, east, west, and center areas. When you are using a dockable toolbar, however, the container only should use two of these: the center and one directional area.
The toolbar should be added to the directional area. The following statements create a vertical, dockable toolbar with three icon buttons:
BorderLayout border = new BorderLayout();
pane.setLayout(border);
JToolBar bar = new JToolBar(SwingConstants.VERTICAL);
ImageIcon play = new ImageIcon("play.gif");
JButton playButton = new JButton(play);
ImageIcon stop = new ImageIcon("stop.gif");
JButton stopButton = new JButton(stop);
ImageIcon pause = new ImageIcon("pause.gif");
JButton pauseButton = new JButton(pause);
bar.add(playButton);
bar.add(stopButton);
bar.add(pauseButton);
add(bar, BorderLayout.WEST);
The next project you undertake during this hour is Tool
, a Java application that includes image icons and a dockable toolbar around. Create an empty Java file called Tool
, enter Listing 16.3 in the file, and save the file.
1: import java.awt.*;
2: import java.awt.event.*;
3: import javax.swing.*;
4:
5: public class Tool extends JFrame {
6: public Tool() {
7: super("Tool");
8: setLookAndFeel();
9: setSize(370, 200);
10: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11:
12: // build toolbar buttons
13: ImageIcon image1 = new ImageIcon("newfile.gif");
14: JButton button1 = new JButton(image1);
15: ImageIcon image2 = new ImageIcon("openfile.gif");
16: JButton button2 = new JButton(image2);
17: ImageIcon image3 = new ImageIcon("savefile.gif");
18: JButton button3 = new JButton(image3);
19:
20: // build toolbar
21: JToolBar bar = new JToolBar();
22: bar.add(button1);
23: bar.add(button2);
24: bar.add(button3);
25:
26: // build text area
27: JTextArea edit = new JTextArea(8, 40);
28: JScrollPane scroll = new JScrollPane(edit);
29:
30: // create frame
31: BorderLayout border = new BorderLayout();
32: setLayout(border);
33: add("North", bar);
34: add("Center", scroll);
35: setVisible(true);
36: }
37:
38: private void setLookAndFeel() {
39: try {
40: UIManager.setLookAndFeel(
41: "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
42: );
43: } catch (Exception exc) {
44: // ignore error
45: }
46: }
47:
48: public static void main(String[] arguments) {
49: Tool frame = new Tool();
50: }
51: }
The Tool
application requires three graphics files that are used to create the icons on the toolbar: newfile.gif
, openfile.gif
, and savefile.gif
. Download these files from the Hour 16 page on the book’s website at www.java24hours.com and save them in the Java24
project folder (or the folder you designated for your Java projects in NetBeans).
Figure 16.3 and Figure 16.4 show two different screenshots of this application as it runs. The toolbar has been moved from its original location (see Figure 16.3) to another edge of the interface (see Figure 16.4).
Having trouble finding this folder? Start a new project in NetBeans: Choose File, New Project, category Java, project type Java application, and then click Next. The Project Location text field should contain the location of the folder where these icons should be saved.
You also can drag a dockable toolbar off an interface entirely. This causes a new window to be opened that contains the toolbar.
Compile the application and try it out by moving the toolbar around. You can move a toolbar by clicking its handle and dragging the toolbar to a different edge of the text area. When you release the toolbar, it is placed along that edge and the text area moves over to make room for it.
Oracle offers a repository of icon graphics that you can use in your own programs. The three icons used in this hour’s workshop are from that collection. To view the graphics, visit http://java.sun.com/developer/techDocs/hi/repository.
This is the last of four hours devoted to Swing, the part of the Java language that supports GUI software.
Although Swing is by far the largest part of the Java class library, most of the classes are used in similar ways. After you know how to create a component, add a component to a container, apply a layout manager to a container, and respond to user input, you can make use of many new Swing classes as you explore the language.
Q. How can I find out about the rest of the Swing classes in the Java class library?
A. On Oracle’s official Java site, the full documentation for the Java class library is published at http://download.oracle.com/javase/7/docs/api. You can see the classes that are included in javax.swing
, java.awt
, and java.awt.event
, the packages that are covered during the preceding four hours. All Swing classes and interfaces are documented, including their constructors, class variables, and instance variables.
Q. Why is a videogame about a barrel-tossing, princess-kidnapping ape and an Italian plumber called Donkey Kong?
A. Donkey Kong was named by Shigeru Miyamoto, who created the game for Nintendo as a coin-operated arcade game in 1981. Miyamoto was under the mistaken impression that the word “donkey” meant “stupid” in English, but by the time Nintendo’s American division learned of it the name had stuck.
Miyamoto’s gorilla/princess/plumber love triangle was inspired by Nintendo’s failed attempt to license Popeye for a videogame. Later videogames established that the original Donkey Kong has become Cranky Kong, an elderly bad-tempered ape who believes that an excessive amount of processing power is devoted to current games compared to his 8-bit heyday.
No pane, no gain: Exercise some brain muscle by answering the following questions about scroll panes, image icons, and other Swing features.
1. What graphics file formats are supported by the ImageIcon
class?
A. GIF
B. GIF and JPEG
C. GIF, PNG, and JPEG
2. What does a JSlider
object’s getValueIsAdjusting()
method accomplish?
A. It determines whether the slider has been changed from its original value.
B. It determines whether the slider is currently being changed in value.
C. Not a lot; this method is a major disappointment to its parent superclass.
3. The Swing library was named after a style of dance band jazz that was popularized in the 1930s and revived in the 1990s. Which of the following is not a real title of a song performed by a Swing musician?
A. “Cement Mixer (Put-ti, Put-ti)”
B. “Sussudio”
C. “Flat Foot Floogie (with the Floy Floy)”
1. C. PNG support in ImageIcon
was added in Java 1.3.
2. B. The getValueIsAdjusting()
method returns true
while the slider is being moved and false
otherwise.
3. B. “Sussudio,” a hit song by Phil Collins in 1985, was five decades too late for Swing. The other two songs are Swing hits by Slim Gaillard, whose gift for gibberish also was evident in the songs “Boot-Ta-La-Za,” “Ra-Da-Da-Da,” “Bingie-Bingie-Scootie,” and “Vout Oreenie.”
To see if you have got the swing of things, try the following activities:
• Create a GUI that includes a combo box in a scroll pane.
• Add event-handling to the MailWriter
application that displays the contents of the to
, subject
, and message
components using System.out.println()
when the Send button is clicked.
To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.
3.137.163.206