ホームページ  >  に質問  >  本文

java - why cannot read int value from JTextField

JTextField t1 = new JTextField(" ");
String a = t1.getText(); 
int intA = Integer.parseInt(a); 
System.out.println(intA);

Error

java.lang.NumberFormatException: For input string: "1 "

附上我的代码

public class Testing extends JPanel {

    public int s;

    public Testing() {

        JPanel p = new JPanel();
        JTextField t1 = new JTextField(" ");
        JTextField t2 = new JTextField(" ");
        JTextField t3 = new JTextField(" ");
        JButton b3 = new JButton("result");

        p.add(t1);
        p.add(t2);
        p.add(t3);
        p.add(b3);
        add(p);

        b3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String a = t1.getText();
                    int intA = Integer.parseInt(a);
                    System.out.println(intA);
                    // String b = t2.getText();
                    //t3.setText(a+"");
                } catch (NumberFormatException ignored) {
                    System.out.println(ignored);
                }
            }
        });
    }

    public static void main(String... arg) {
        Testing p = new Testing();
        JFrame frame = new JFrame();
        frame.add(p);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }
}
大家讲道理大家讲道理2742日前579

全員に返信(2)返信します

  • 巴扎黑

    巴扎黑2017-04-18 10:58:26

    //ガイドパッケージ。
    import javax.swing.*;
    import java.awt.event.*;

    クラス JTextFieldDemo
    {

    リーリー

    }

    要約:
    上記の問題は、コンテンツを入力した後に jtf.getText(); メソッドを実行する必要があるために発生しますが、投稿者が示すコードでは実行時に実行できるため、エラーが報告されます。 (私の勝手な意見です、ふふ)

    返事
    0
  • 迷茫

    迷茫2017-04-18 10:58:26

    @Sjs_k さん、ご回答ありがとうございます

    JTextField t1 = new JTextField(""); 改去 JTextField t1 = new JTextField(5);を入れるだけです

    返事
    0
  • キャンセル返事