문제

I am a beginner in Java GUI's and for class I need to make a program that converts Fahrenheit to Celsius and vice versa. I wanted to make a GUI program that utilized a button but can't find any posts online that would help me. I am having trouble with the button actually working properly. It converts from Fahrenheit to Celsius just fine, but will not convert Celsius to Fahrenheit. I know there is an obvious error in the logic but I cannot for the life of me figure it out. Any help would be much appreciated.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;

    @SuppressWarnings("serial")
    public class Temperature_Converter extends JFrame{
    private static final double CelsiusTOFarenheit = 9.0 / 5.0;
    private static final double FahrenheitTOCelsius = 5.0 / 9.0;
    private static final int offset = 32;
    private JLabel LFahrenheit, LCelsius; //Labels
    private JTextField TFFahrenheit, TFCelsius; //Text Fields
    private JButton BConvert; //Convert Button
    private ConvertButtonHandler ConvButtonHandler;

    public Temperature_Converter() {
    setTitle("Temperature Converter");
    Container pane = getContentPane();
    pane.setLayout(new GridLayout(1,5));

    LFahrenheit = new JLabel("Farenheit:", JLabel.CENTER);
        pane.add(LFahrenheit);
    TFFahrenheit = new JTextField();
        pane.add(TFFahrenheit);
    BConvert = new JButton("Convert");
        pane.add(BConvert);
            ConvButtonHandler = new ConvertButtonHandler();
            BConvert.addActionListener(ConvButtonHandler);
    LCelsius = new JLabel("Celsius:", JLabel.CENTER);
        pane.add(LCelsius);
    TFCelsius = new JTextField();
        pane.add(TFCelsius);

    setSize(600, 85);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
 private class ConvertButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            double celsius = 0, fahrenheit = 0;

            DecimalFormat twoDigits = new DecimalFormat("0.00");     
                    celsius = Double.parseDouble(TFCelsius.getText());
                    fahrenheit = Double.parseDouble(TFFahrenheit.getText());
                        celsius = (fahrenheit - offset) * FahrenheitTOCelsius;
                        fahrenheit = celsius * CelsiusTOFarenheit + offset;
                            TFCelsius.setText(" "+ twoDigits.format(celsius));
                            TFFahrenheit.setText(" "+ twoDigits.format(fahrenheit));       
    }
 }

public static void main(String[] args) {
    new Temperature_Converter();
}

}

도움이 되었습니까?

해결책

Here is what might help you : leave blank the text field which you want to be populated( leave blank fahrenheit if you want to convert from celsius to fahrenheit ).

 @Override
public void actionPerformed(final ActionEvent e) {
    double celsius = 0, fahrenheit = 0;
    DecimalFormat twoDigits = new DecimalFormat("0.00");
    if (Temperature_Converter.this.TFCelsius.getText() == null || "".equals(Temperature_Converter.this.TFCelsius.getText().trim())) {
        // convert from fahrenheit to celsius
        fahrenheit = Double.parseDouble(Temperature_Converter.this.TFFahrenheit.getText());
        celsius = (fahrenheit - Temperature_Converter.offset) *   Temperature_Converter.FahrenheitTOCelsius;
        Temperature_Converter.this.TFCelsius.setText(" " + twoDigits.format(celsius));
    } else if (Temperature_Converter.this.TFFahrenheit.getText() == null || "".equals(Temperature_Converter.this.TFFahrenheit.getText().trim())) {
           // convert from celsius to fahrenheit
           celsius = Double.parseDouble(Temperature_Converter.this.TFCelsius.getText());
           fahrenheit = celsius * Temperature_Converter.CelsiusTOFarenheit + Temperature_Converter.offset;
           Temperature_Converter.this.TFFahrenheit.setText(" " + twoDigits.format(fahrenheit));
    }
}

Edit : You can validate the user input text and alert the user if there are something else then numbers introduced as a temperature.

try {
    fahrenheit = Double.parseDouble(Temperature_Converter.this.TFFahrenheit.getText());
} catch (NumberFormatException e1) {
     //alert the user       
    JOptionPane.showMessageDialog(null, "You are allowed to introduce numbers only for temperature");
    return;
}

다른 팁

Assuming that I have to put one value in the Fahrenheit field and one in the Celsius field and they should be calculated at the same time, you have to kind of "cache" your calculation values in other variables than the ones you got from the textfields.

When you do this:

celsius = Double.parseDouble(TFCelsius.getText());
fahrenheit = Double.parseDouble(TFFahrenheit.getText());
celsius = (fahrenheit - offset) * FahrenheitTOCelsius;
fahrenheit = celsius * CelsiusTOFarenheit + offset;

the result of your first calculation (the new Celsius value) will be used in the second calculation, leading to the very same result as the value in the Fahrenheit field originally was (because it just converts the value to Celsius and than back again)

The solution for your problem is to safe your results in new variables like:

celsius = Double.parseDouble(TFCelsius.getText());
fahrenheit = Double.parseDouble(TFFahrenheit.getText());
double celsiusNew = (fahrenheit - offset) * FahrenheitTOCelsius;
double fahrenheitNew = celsius * CelsiusTOFarenheit + offset;
TFCelsius.setText(" "+ twoDigits.format(celsiusNew));
TFFahrenheit.setText(" "+ twoDigits.format(fahrenheitNew));

This will do the trick.

Edit: read the other two answers as well for making your program more user-friendly and bulletproof.

i think that your problem with The text Field ,if you didn't input numbers in the two text fields you will get "empty String" problem which cannot convert it to Double , so you need to check that you string not equal to empty

so , your problem is in this two line :

 celsius = Double.parseDouble(TFCelsius.getText());
 fahrenheit = Double.parseDouble(TFFahrenheit.getText());

to solve it , you can make like this , For Example :

if (!TFCelsius.getText().equals("")) {
     celsius = Double.parseDouble(TFCelsius.getText());
 } else {
     ////i don't know what the value but make it equal 0
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top