import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;


public class TemperatureConverter implements ActionListener {

    private JTextPane outputPane;
    private JTextField inputField;

    public Component createContent() {
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BorderLayout(3,3));

        contentPanel.add(createOutputPane(), BorderLayout.CENTER);
        contentPanel.add(createInputField(), BorderLayout.PAGE_START);
        
        return contentPanel;
    }

    private Component createInputField() {
        this.inputField = new JTextField();
        this.inputField.addActionListener(this);
        return this.inputField;
    }

    private Component createOutputPane() {
        this.outputPane = new JTextPane();
        this.outputPane.setContentType("text/html");
        this.outputPane.setEditable(false);
        return this.outputPane;
    }

    public void actionPerformed(ActionEvent e) {
        String inputStr = this.inputField.getText();
        try {
            int inputInt = Integer.parseInt(inputStr);
            setOutput(inputInt);
        } catch(NumberFormatException nfe) {
            this.outputPane.setText("<h1>Wrong Input</h1>\n"+nfe);
        }
    }

    private void setOutput(int inputInt) {
        StringBuilder sb = new StringBuilder();
        sb.append("<h1>Konvertierung</h1>");
        sb.append("<ul>\n");
        sb.append("<li> "+inputInt+"C = "+celsiusToFahrenheit(inputInt)+"F\n");
        sb.append("<li> "+inputInt+"F = "+fahrenheitToCelsius(inputInt)+"C\n");
        sb.append("</ul>\n");
        this.outputPane.setText(sb.toString());
    }

    private static int fahrenheitToCelsius(int fahrenheit) {
        // TCelsius = ( TFahrenheit - 32 ) × 5 / 9
        return ((fahrenheit - 32) * 5) / 9;
    }
    private static int celsiusToFahrenheit(int celsius) {
        // TFahrenheit = (( TCelsius × 9 ) / 5 ) + 32
        return ((celsius * 9) / 5) + 32;
    }

    public static void main(String[] args) {
        TemperatureConverter temperatureConverter = new TemperatureConverter();
        JFrame frame = new JFrame("TemperatureConverter");
        frame.add(temperatureConverter.createContent());
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

