Java Reference
In-Depth Information
fahrenheitTF . The necessary code is placed within the body of the method
actionPerformed .
We now describe the steps of the method actionPerformed . The temperature
in Celsius is contained in the JTextField celsiusTF .Weusethemethod
getText of the class JTextField to retrieve the temperature in celsiusTF .
However, the value returned by the method getText is in string form, so we
use the method parseDouble of the class Double to convert the numeric
string into a decimal value. It follows that we need a variable of type double ,
say, celsius , to store the temperature in Celsius. We accomplish this with the
following statement:
celsius = Double.parseDouble(celsiusTF.getText());
We also need a variable of type double , say, fahrenheit , to store the equivalent
temperature in Fahrenheit. Because we want to display the temperature to two
decimal places, we use the method format of the class String .
We can now write the definition of the class CelsHandler as follows:
6
private class CelsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double celsius, fahrenheit;
celsius =
Double.parseDouble(celsiusTF.getText());
fahrenheit = celsius * CTOF + OFFSET;
fahrenheitTF.setText(String.format("%.2f",
fahrenheit));
}
}
We can now create an object of type CelsHandler as follows:
private CelsHandler celsiusHandler;
celsiusHandler = new CelsHandler();
Having created a listener, you must associate this handler with the corresponding
JTextField celsiusTF . The following code does this:
celsiusTF.addActionListener(celsiusHandler);
Search WWH ::




Custom Search