The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: User Interfaces that Swing: A Quick Start Guide

Example Three: CelsiusConverter

Topics illustrated in this example: Our next example, CelsiusConverter(in a .java source file), does something that's somewhat useful: It is a simple conversion tool. The user enters a temperature in degrees Celsius and clicks the Convert... button, and a label displays the equivalent in degrees Fahrenheit.

The CelsiusConverter GUI

Let's examine the code to see how CelsiusConverter parses the number entered in the JTextField. First, here's the code that sets up the JTextField:
JTextField tempCelsius = null;
...
tempCelsius = new JTextField(5);
The integer argument passed in the JTextField constructor, 5 in the example, indicates the number of columns in the field. This number is used along with metrics provided by the current font to calculate the field's preferred width. This number does not limit how many character the user can enter.

We want to handle the button-click event, so we add an event listener to the button.

JButton convertTemp;
...
convertTemp.addActionListener(this);
...
public void actionPerformed(ActionEvent event) {
    // Parse degrees Celsius as a double and convert to Fahrenheit.
    int tempFahr = (int)((Double.parseDouble(tempCelsius.getText())) 
                         * 1.8 + 32);
    fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
The getText method is called on the text field, tempCelsius, to retrieve the data within it. Next, the parseDouble method parses the text as a double before converting the temperature and casting the result to an integer. Finally, the setText method is called on the fahrenheitLabel to display the converted temperature. All this code is found in the event handler for the button, as the conversion happens only once the button is clicked.

Note: You can make a JButton be the default button. At most one button in a top-level container can be the default button. The default button typically has a highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and the user presses the Return or Enter key. The exact implementation depends on the look and feel. You set the default button by invoking the setDefaultButton method on a top-level container's root pane:
//In the constructor for a JDialog subclass:
getRootPane().setDefaultButton(setButton);

Adding HTML

You can use HTML to specify the text on some Swing components, such as buttons and labels. We can spice up the CelsiusConverter program by adding HTML text to the fahrenheitLabel and adding an image to the convertTemp button. The revised program is CelsiusConverter2(in a .java source file).

The improved CelsiusConverter2 application with colored fonts on the Fahrenheit label and a graphic on the button.

First, let's look at how we specify the HTML tags for the fahrenheitLabel. As you can see from this code, the temperature (tempFahr) is displayed one of three different colors, depending on how hot or cold the converted temperature is:
// Set fahrenheitLabel to new value and font color based on temperature.
if (tempFahr <= 32) {
    fahrenheitLabel.setText("<html><font color=blue>" + tempFahr 
                            + "&#176  Fahrenheit </font></html>");

} else if (tempFahr <= 80) {
    fahrenheitLabel.setText("<html><font color=green>" + tempFahr 
                            + "&#176  Fahrenheit </font></html>");

} else {
    fahrenheitLabel.setText("<html><font color=red>" + tempFahr 
                            + "&#176  Fahrenheit </font></html>");
}
To add HTML code to the label, simply put the <HTML> tag at the beginning of a string, and then use any valid HTML code in the remainder of the string. Using HTML can be useful for varying the text font or color within a button and for adding line breaks. To display the degree symbol, we use the HTML code &#176.

Note: If the string is to be all one size and color, you don't have to use HTML. You can call the setFont(in the API reference documentation) method to specify the font of any component.

Warning: Don't use HTML in buttons unless you're absolutely sure that the program is running in a release that supports this feature. In releases that don't support HTML text, such as Swing 1.1, putting HTML in a button results in one ugly-looking button whose label starts (not surprisingly) with <HTML>.

Adding an Icon

Some Swing components can be decorated with an icon--a fixed-size image. A Swing icon is an object that adheres to the Icon interface. Swing provides a particularly useful implementation of the Icon interface: ImageIcon. ImageIcon paints an icon from a GIF or a JPEG image. Here's the code that adds the arrow graphic to the convertTemp button:
ImageIcon icon = new ImageIcon("images/convert.gif", 
                               "Convert temperature");
...
convertTemp = new JButton(icon);
The first argument of the ImageIcon constructor specifies the file to load, relative to the directory containing the application's class file. The second argument provides a description of the icon that assistive technologies can use.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.