Java Reference
In-Depth Information
Similarly, we can create and register an action listener with the text field fahrenheitTF .
The necessary code is:
private class FahrHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double celsius, fahrenheit;
fahrenheit =
Double.parseDouble(fahrenheitTF.getText());
celsius = (fahrenheit - OFFSET) * FTOC;
celsiusTF.setText(String.format("%.2f",
celsius));
}
}
private FahrHandler fahrenheitHandler;
fahrenheitHandler = new FahrHandler(); //instantiate the object
fahrenheitTF.addActionListener(fahrenheitHandler);
//add the action listener
Now that we have created the necessary GUI components and the programming
code, we can put everything together to create the complete program.
You can start with the window creation program and then add all the components,
handlers, and classes developed. You also need the necessary import statements. In
this case, they are:
PUTTING IT
TOGETHER
import java.awt.*; //for the class Container
import java.awt.event.*; //for events
import javax.swing.*; //for JLabel and JTextField
Thus, you have the following Java program:
//*************************************************************
//Author: D.S. Malik
//
//Java program to convert the temperature between Celsius and
//Fahrenheit.
//*************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
Search WWH ::




Custom Search