import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TemperatureGUI { private int WIDTH = 250; private int HEIGHT = 125; private JFrame frame; private JPanel panel; private JLabel inputLabel, outputLabel, resultLabel; private JTextField inTemp; private JButton f2cButton, c2fButton; //----------------------------------------------------------------- // Sets up the GUI. //----------------------------------------------------------------- public TemperatureGUI(){ frame = new JFrame ("Temperature Conversion"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); inputLabel = new JLabel ("Enter Input temperature:"); outputLabel = new JLabel ("Converted Temperature: "); resultLabel = new JLabel ("---"); f2cButton = new JButton ("Convert F to C"); f2cButton.setEnabled(true); f2cButton.addActionListener( new f2cListener()); c2fButton = new JButton ("Convert C to F"); c2fButton.setEnabled(true); c2fButton.addActionListener( new c2fListener()); inTemp = new JTextField (5); // fahrenheit.addActionListener (new TempListener()); panel = new JPanel(); panel.setPreferredSize (new Dimension(WIDTH, HEIGHT)); panel.setBackground (Color.yellow); panel.add (inputLabel); panel.add (inTemp); panel.add (outputLabel); panel.add (resultLabel); panel.add (f2cButton); panel.add (c2fButton); frame.getContentPane().add (panel); } //----------------------------------------------------------------- // Displays the primary application frame. //----------------------------------------------------------------- public void display(){ frame.pack(); frame.show(); } //***************************************************************** // Represents an action listener for the temperature input field. //***************************************************************** private class TempListener implements ActionListener { //-------------------------------------------------------------- // Performs the conversion when the enter key is pressed in // the text field. //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celciusTemp; String text = inTemp.getText(); fahrenheitTemp = Integer.parseInt (text); celciusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celciusTemp)); } } private class f2cListener implements ActionListener { public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celciusTemp; String text = inTemp.getText(); fahrenheitTemp = Integer.parseInt(text); celciusTemp = (fahrenheitTemp - 32) * 5/9; resultLabel.setText(Integer.toString(celciusTemp)); } } private class c2fListener implements ActionListener { public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celciusTemp; String text = inTemp.getText(); celciusTemp = Integer.parseInt(text); fahrenheitTemp = celciusTemp* 9/5 + 32; resultLabel.setText(Integer.toString(fahrenheitTemp)); } } }