Our next example, CelsiusConverter, [1] 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.
|
Figure 101. 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.
Figure 102. The improved CelsiusConverter2 [1] application with colored fonts on the Fahrenheit label and a graphic on the button.
[1] CelsiusConverter2.java is included on the CD and is available online. See Code Samples (page 390).
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("
" + tempFahr + "° Fahrenheit
"); } else if (tempFahr <= 80) { fahrenheitLabel.setText("
" + tempFahr + "° Fahrenheit
"); } else { fahrenheitLabel.setText("
" + tempFahr + "° Fahrenheit
"); }
To add HTML code to the label, simply put the
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 "°".
Note
If the string is to be all one size and color, you don't have to use HTML. You can call the setFont method to specify the font of any component. For more information, see the API documentation on the CD or online at: http://java.sun.com/j2se/1.3/docs/api/javax/swing/JComponent.html#setFont(java.awt.Font).
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
.
Adding an Icon
Some Swing components can be decorated with an icona 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.
Getting Started
Object-Oriented Programming Concepts
Language Basics
Object Basics and Simple Data Objects
Classes and Inheritance
Interfaces and Packages
Handling Errors Using Exceptions
Threads: Doing Two or More Tasks at Once
I/O: Reading and Writing
User Interfaces That Swing
Appendix A. Common Problems and Their Solutions
Appendix B. Internet-Ready Applets
Appendix C. Collections
Appendix D. Deprecated Thread Methods
Appendix E. Reference