Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
2
Indexable
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingTemperatureConverter {
    private JFrame frame;
    private JTextField celsiusField;
    private JTextField fahrenheitField;

    public SwingTemperatureConverter() {
        frame = new JFrame("Temperature Converter");
        frame.setLayout(new GridLayout(2, 2));

        JLabel celsiusLabel = new JLabel("Celsius:");
        celsiusField = new JTextField();
        JLabel fahrenheitLabel = new JLabel("Fahrenheit:");
        fahrenheitField = new JTextField();

        frame.add(celsiusLabel);
        frame.add(celsiusField);
        frame.add(fahrenheitLabel);
        frame.add(fahrenheitField);

        celsiusField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                convertToCelsius();
            }
        });

        fahrenheitField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                convertToFahrenheit();
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void convertToCelsius() {
        try {
            double fahrenheit = Double.parseDouble(fahrenheitField.getText());
            double celsius = (fahrenheit - 32) * 5.0 / 9.0;
            celsiusField.setText(String.format("%.2f", celsius));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(frame, "Invalid input. Please enter a valid number in Fahrenheit.");
        }
    }

    private void convertToFahrenheit() {
        try {
            double celsius = Double.parseDouble(celsiusField.getText());
            double fahrenheit = (celsius * 9.0 / 5.0) + 32;
            fahrenheitField.setText(String.format("%.2f", fahrenheit));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(frame, "Invalid input. Please enter a valid number in Celsius.");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SwingTemperatureConverter();
            }
        });
    }
}