Example Three: CelsiusConverter

 <  Day Day Up  >  

graphics/cd_icon.gif

Our next example, CelsiusConverter , [5] is actually useful: It's a simple temperature conversion tool. When the user enters a temperature in degrees Celsius and clicks the Convert button, a label displays the equivalent temperature in degrees Fahrenheit (see Figure 7).

[5] To run CelsiusConverter using Java Web Start, click the CelsiusConverter link on the RunExamples/learn.html page on the CD. You can find the source files here: JavaTutorial/uiswing/learn/example-1dot4/index.html#CelsiusConverter .

Figure 7. The CelsiusConverter GUI.

graphics/02fig07.gif

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, which is used by layout managers. This number doesn't limit how many characters the user can enter.

We want to perform the conversion when the user clicks the button or presses Enter in the text field. To do so, we add an action event listener to the convertTemp button and tempCelsius text field.

 convertTemp.addActionListener(this); tempCelsius.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 event-handling code goes into the actionPerformed method. It calls the getText method on the text field, tempCelsius , to retrieve the data within it. Next it uses the parseDouble method to parse the text as a double-precision floating-point number before converting the temperature and casting the result to an integer. Finally, it calls the setText method on the fahrenheitLabel to make the label display the converted temperature.

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net