Java Reference
In-Depth Information
Notice that these variables are needed in each event handler.
The formulas to convert the temperature from Fahrenheit to Celsius and vice versa
use the special values 32 , 9.0/5.0 , and 5.0/9.0 , which we will declare as named
constants as follows:
private static final double FTOC = 5.0 / 9.0;
private static final double CTOF = 9.0 / 5.0;
private static final int OFFSET = 32;
As in the GUI, you need two labels—one to label the text field corresponding to the
Celsius value and another to label the text field corresponding to the Fahrenheit
value. Therefore, the following statements are needed:
private JLabel celsiusLabel;
//label Celsius
private JLabel fahrenheitLabel;
//label Fahrenheit
6
celsiusLabel = new JLabel("Temp in Celsius: ",
SwingConstants.RIGHT); //object instantiation
fahrenheitLabel = new JLabel("Temp in Fahrenheit: ",
SwingConstants.RIGHT); //object instantiation
You also need two JTextField objects. The necessary Java code is:
private JTextField celsiusTF;
//text field Celsius
private JTextField fahrenheitTF;
//text field Fahrenheit
celsiusTF = new JTextField(7); //object instantiation
fahrenheitTF = new JTextField(7); //object instantiation
Now you need a window to display the labels and the text fields. Because a window
is an object of type JFrame , the class containing the application program that we
create will extend the definition of the class JFrame . We will set the width of the
window to 500 pixels and the height to 50 pixels. We'll call the class containing the
application program TempConversion . The application will look like this:
//Java program to convert the temperature from Celsius to
//Fahrenheit and vice versa.
import javax.swing.*;
public class TempConversion extends JFrame
{
private static final int WIDTH = 500;
private static final int HEIGHT = 50;
private static final double FTOC = 5.0 / 9.0;
private static final double CTOF = 9.0 / 5.0;
private static final int OFFSET = 32;
Search WWH ::




Custom Search