Download the JDK
Search the Tutorials
Hide the TOC
Trail: Creating a GUI with JFC/Swing
Lesson: Learning Swing by Example
Learning Swing by Example
Example One: Your First Swing Program
Example Two: `SwingApplication`
Example Three: `CelsiusConverter`
Example Four: An Improved `CelsiusConverter`
Example Five: `LunarPhases`
Example Six: `VoteDialog`
Summary
Home Page > Creating a GUI with JFC/Swing > Learning Swing by Example
« Previous • Trail • Next »
Example Three: `CelsiusConverter`

> Our next example, `CelsiusConverter`is actually 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.

> 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 does not limit how many character 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.

« Previous • Trail • Next »
Previous page: Example Two: `SwingApplication`
Next page: Example Four: An Improved `CelsiusConverter`