我正在尝试编写GUI温度转换器。它有一个JTextField和两个JButton。 TextField接受用户想要转换的温度,用户按下相应的按钮。每当我点击任何一个按钮时,我得到一个“线程异常”AWT-EventQueue-0“java.lang.NumberFormatException:empty String”错误。请帮助!
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 :(得分:2)
问题是您正在动作侦听器中重新创建一个新帧:new tempcon().getTempC()
。
这些新框架中的文本字段显然是空的,您会收到错误消息。
考虑在任何地方引用tempcon
的相同实例,只需替换
new tempcon().getTempC();
带
getTempC();
,它将调用外部getTempC()
实例的tempcon
方法。