2017-11-06 5 views
0

私はGUI温度コンバータを書こうとしています。 1つのJTextFieldと2つのJButtonがあります。 TextFieldは、ユーザが変換したい温度を受け入れ、ユーザが適切なボタンを押す。 AWT-EventQueue-0 "java.lang.NumberFormatException:空の文字列"というエラーが表示されます。助けてください!次のコードで "Number format exception/empty string"エラーを解決するにはどうすればよいですか?

import javax.swing.*; 
import java.awt.*; 

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

ええ、私はそれを修正するために何ができるかわかりません – Abby

答えて

1

問題は、アクションリスナーに新しいフレームを再作成することです。new tempcon().getTempC()

これらの新しいフレームのテキストフィールドは明らかに空で、エラーが発生します。

は、それは単に外tempconインスタンスのgetTempC()メソッドを呼び出すであろう、

getTempC();

new tempcon().getTempC();

を交換さどこでもtempconの同じインスタンスを参照することを検討してください。

+0

私は問題を解決していないのですが、恐れています。この場合、IDEはメソッドを見つけることができません。 – Abby

+0

私は別の方法で問題を解決することができました – Abby

関連する問題