// File: FahrenheitToCelsius.java // Simple GUI example // Prepared by Dr. Spiegel import java.awt.*; import javax.swing.*; import java.awt.event.*; class ConvertTemperatures extends JFrame implements ActionListener, WindowListener { JLabel directions; JTextField fahrenheit; JLabel celsius; ConvertTemperatures(String s) { super(s); // Need a JPanel to put items on. We'll use a BorderLayout JPanel panel=new JPanel(new BorderLayout(5,5)); // Set JFrame size. If you don't do this, only the top bar will appear setSize(250,100); // Set JPanel size panel.setSize(250,130); // Set the JPanel's background panel.setBackground(Color.blue); // Add a window listener to the JFrame addWindowListener(this); // Now, place everything into the JPanel // First, the prompt directions = new JLabel("Enter temperature in Fahrenheit:"); directions.setForeground(Color.yellow); panel.add("West",directions); // Now, the text field to input the temperature fahrenheit = new JTextField(2); fahrenheit.setSize(15,10); // Place it on the panel. Note, that if you don't want it to appear as // tall as it does, you should place the JTextField into a JPanel // with a FlowLayout and then that new JPanel into the main JPanel panel.add("East",fahrenheit); // Need a listener for events on the text field fahrenheit.addActionListener(this); // Add a label to hold the result celsius = new JLabel(" "); celsius.setFont(new Font("TimesRoman 16 point bold.", 20, 25)); celsius.setForeground(Color.red); panel.add("South",celsius); // Place the JPanel on the JFrame getContentPane().add(panel); setVisible(true); } public void windowClosed(WindowEvent event) {} public void windowDeiconified(WindowEvent event) {} public void windowIconified(WindowEvent event) {} public void windowActivated(WindowEvent event) {} public void windowDeactivated(WindowEvent event) {} public void windowOpened(WindowEvent event) {} public void windowClosing(WindowEvent event) { System.exit(0); } public void actionPerformed(ActionEvent event) { int f = Integer.parseInt(fahrenheit.getText()); long c = Math.round(5.0*(f - 32)/9.0); fahrenheit.setText(""); celsius.setText(f + "\u00B0F = " + c + "\u00B0C"); } } class TestConvertTemperatures { public static void main(String[] args) { new ConvertTemperatures("Fahrenheit To Celsius Conversion"); } }