import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FahrenheitGUIwithButton { private int WIDTH = 300; private int HEIGHT = 75; private JFrame frame; private JPanel panel; private JLabel inputLabel, outputLabel, resultLabel; private JTextField fahrenheit; private JButton convertButton; //----------------------------------------------------------------- // Sets up the GUI. //----------------------------------------------------------------- public FahrenheitGUIwithButton(){ frame = new JFrame ("Temperature Conversion"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celcius: "); resultLabel = new JLabel ("---"); convertButton = new JButton ("Convert"); convertButton.setEnabled(true); convertButton.addActionListener( new ButtonListener()); fahrenheit = 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 (fahrenheit); panel.add (outputLabel); panel.add (resultLabel); panel.add (convertButton); 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 = fahrenheit.getText(); fahrenheitTemp = Integer.parseInt (text); celciusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celciusTemp)); } } private class ButtonListener implements ActionListener { public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celciusTemp; String text = fahrenheit.getText(); fahrenheitTemp = Integer.parseInt(text); celciusTemp = (fahrenheitTemp - 32) * 5/9; resultLabel.setText(Integer.toString(celciusTemp)); in } } }