簡體   English   中英

是什么導致以下代碼中的“數字格式異常/空字符串”錯誤?

[英]What causes “Number format exception / empty string” error in the following code?

我正在嘗試編寫GUI溫度轉換器。 它具有一個JTextField和兩個JButton。 TextField接受用戶想要轉換的溫度,然后用戶按下相應的按鈕。 每當我單擊任何一個按鈕時,都會收到“線程“ AWT-EventQueue-0”中的異常” java.lang.NumberFormatException:空字符串”錯誤。 請幫忙!

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();
}
}

問題在於您正在動作監聽器中重新創建一個新框架: new tempcon().getTempC()

這些新框架中的文本字段顯然為空,您會收到錯誤消息。

考慮到各處都引用相同的tempcon實例,只需替換

new tempcon().getTempC();

getTempC();

,它將調用外部tempcon實例的getTempC()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM