Code:
package tempconv; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TempConv extends JFrame { private JLabel CelL, FahrL; private JTextField CelTF, FahrTF; private CelsiusHandler cHandler; private FahrenheitHandler fHandler; private static final double FTOC = 5.0 / 9.0; private static final double CTOF = 9.0 / 5.0; private static final int OFFSET = 32; private static final int WIDTH = 400; private static final int HEIGHT = 100; public void TempConv() //constructor { //set labels CelL = new JLabel("Temp in Celsius: ", SwingConstants.RIGHT); FahrL = new JLabel("Temp in Fahrenheit: ", SwingConstants.RIGHT); //set text field cHandler = new CelsiusHandler(); CelTF = new JTextField(10); //declare action listener object of its class fHandler = new FahrenheitHandler(); FahrTF = new JTextField(10); //set title for window setTitle("Temperature Conversion"); //get the container Container pane = getContentPane(); //set layout pane.setLayout(new GridLayout(1, 4)); //Add info to window's content pane pane.add(CelL); pane.add(CelTF); pane.add(FahrL); pane.add(FahrTF); //register action listener CelTF.addActionListener(cHandler); FahrTF.addActionListener(fHandler); //set dimension setSize(WIDTH, HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private class CelsiusHandler implements ActionListener { public void actionPerformed(ActionEvent e) { double celsius, fahrenheit; celsius = Double.parseDouble(CelTF.getText()); fahrenheit = CTOF * celsius + OFFSET; FahrTF.setText(String.format("%.2f" + celsius)); } } private class FahrenheitHandler implements ActionListener { public void actionPerformed(ActionEvent e) { double celsius, fahrenheit; fahrenheit = Double.parseDouble(FahrTF.getText()); celsius = FTOC * (fahrenheit -32); CelTF.setText(String.format("%.2f", +celsius)); } } public static void main(String[] args) { TempConv outputTable = new TempConv(); } }
Comment