1

I am trying to write a GUI temperature converter. It has one JTextField and two JButtons. TextField accepts the temperature which the user wants to convert and the user presses the appropriate button. Whenever I click on anyone of the buttons, I get a "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String" error. Please Help!

public class tempcon extends JFrame {
  private JPanel panel;
  private JLabel messageLabel;
  public JTextField tempC; 
  private JButton calcButton, calcButton1;
  private final int WINDOW_WIDTH = 300;
  private final int WINDOW_HEIGHT = 140;

public tempcon() {
  setTitle("Temperature convertion");
  setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  buildPanel();
  add(panel);
  setVisible(true);
}

public double getTempC(){
 return Double.parseDouble(tempC.getText());
}

private void buildPanel() {
    tempC = new JTextField(10);
    messageLabel = new JLabel("Enter tempurture");
    calcButton = new JButton("Convert to Fahrenheit");
    calcButton1 = new JButton("Convert to Celcius");
    calcButton.addActionListener(new CalcButtonListener());
    calcButton1.addActionListener(new CalcButtonListener1());
    panel = new JPanel();
    panel.add(messageLabel);
    panel.add(tempC);
    panel.add(calcButton);
    panel.add(calcButton1);

}

public static void main(String[] args){
 new tempcon().buildPanel();   
}
}

class CalcButtonListener1 implements ActionListener {
 public void actionPerformed(ActionEvent e) {
        double input;
        double temp;
        input = new tempcon().getTempC();
        temp = input * 1.8 + 32;
        JOptionPane.showMessageDialog(null, "That is " + temp + " 
  degrees Celsius.");
    }

}

 class CalcButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        double input;
        double temp;
        input = new tempcon().getTempC();
        temp = (input - 32)*1.8;
        JOptionPane.showMessageDialog(null, "That is " + temp + " 
 degrees Fehrenheit.");
}

public static void main(String[] args) {
tempcon myTempWindowInstance = new tempcon();
}
}
0

1 Answer 1

2

The problem is that you are recreating a new frame in your action listeners : new tempcon().getTempC() .

The textfields in these new frames are obviously empty and you get your error.

Consider referring to the same instance of tempcon everywhere, that is simply replace

new tempcon().getTempC();

with

getTempC();

, which will call the getTempC() method of the outer tempcon instance .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.