// Temperature conversion program based on 5C, page 247 in Mercer Text // By Dan Hyde, March 7, 2006 import javax.swing.*; // need for graphics import java.awt.*; // need for graphics import java.awt.event.*; // need for listeners import java.text.DecimalFormat; // need for DecimalFormat class public class TempConversion2 extends JFrame { //instance variables JLabel fahrLabel; JTextField fahrTextField; JLabel celLabel; JTextField celTextField; // create a DecimalFormat object for printing double values DecimalFormat onePlace = new DecimalFormat("0.0"); // constructor public TempConversion2() { // Set the title on the title bar setTitle("Temp Converter"); // Set location of upper left corner of window setLocation(400, 400); // Set size of window to be 150 pixels wide by 80 pixels high setSize(200, 80); // When user closes window, the program terminates setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a container associated with the window // to hold graphical components Container contentPane = getContentPane(); // Set the Layout to GridLayout with 2 rows and 2 columns. // 4 pixels separate the horizontal and vertical parts GridLayout grid2By2 = new GridLayout(2, 2, 4, 4); // set Layout of container to be grid2By2. contentPane.setLayout(grid2By2); // Initialize graphical components: JLabel and JTextField celLabel = new JLabel("Celcius:", SwingConstants.RIGHT); celTextField = new JTextField(""); fahrLabel = new JLabel("Fahrenheit:", SwingConstants.RIGHT); fahrTextField = new JTextField(""); // Add graphical components to container // in the order for the Layout contentPane.add(celLabel); contentPane.add(celTextField); contentPane.add(fahrLabel); contentPane.add(fahrTextField); // Create and register listeners on the two JTextFields MyListener1 listenerCelText = new MyListener1(); celTextField.addActionListener(listenerCelText); MyListener2 listenerFahrText = new MyListener2(); fahrTextField.addActionListener(listenerFahrText); } /// inner class private class MyListener1 implements ActionListener { public MyListener1() { } public void actionPerformed(ActionEvent e1) { double cel; String fahrString; cel = Double.parseDouble(celTextField.getText()); fahrString = "" + onePlace.format((cel * 9.0 /5.0 + 32.0)); fahrTextField.setText(fahrString); } } /// end of inner class /// inner class private class MyListener2 implements ActionListener { public MyListener2() { } public void actionPerformed(ActionEvent e1) { double fahr; String celString; fahr = Double.parseDouble(fahrTextField.getText()); celString = "" + onePlace.format((5.0 / 9.0 * (fahr - 32.0))); celTextField.setText(celString); } } /// end of inner class public static void main(String[] args) { // Create a window as JFrame object TempConversion2 theWindow = new TempConversion2(); // Make the window visible to the user theWindow.setVisible(true); } }