For input string: “” when textfields are filled ou

2019-08-28 08:28发布

I am writing a program in Java where I got some textfields and a button.

I get a java.lang.NumberFormatException: For input string: "" even though I have filled out all the textfields when running the program.

My code looks something like this:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        method();
    }
}
            );




public void method() { 
    try { 
        String string1 = textfield1.getText();
        String string2 = textfield2.getText();
        String string3 = textfield3.getText();
        if ( string1.length() == 0 || string2.length() == 0 || string3.length() == 0) { 
            System.out.println("fill in the required text fields");
            return;
        } 
        int number = Integer.parseInt(textfield3.getText());
        //do something
    }
    catch ( NumberFormatException e ) { 
        System.out.println("Wrong format");
    }
}

EDIT:

See more code here

1条回答
虎瘦雄心在
2楼-- · 2019-08-28 09:23

I have tested your program a little bit and you have a problem with the text field, because of the creation of your panel and switching which one is active.

In the constructor you call the something() method which creates the JTextField. When the button is clicked you call again something() and a new JTextField is generated which you also add to the panel.

So you have two JTextFields on the GUI at the exact same position but only a reference to one of them (the last one created).

When you click the button which will call method(). The hidden TextField is asked for his text (this is how it works on my pc) and this is always empty because I can only write into the one I see.

An easy fix to this is to change the method actionPerformed:

@Override
public void actionPerformed( ActionEvent e ) {
    if ( e.getSource() == button1 ) {
        present = something;
        button1.setVisible(false);
        //something();
        visiblePanel();
        previous = something;
    }

}

So I avoid the new creation of the JTextField but visiblePanel() ensures the TextField and second button are shown.

After this change I can type in "sadda" press the button and see the output "Numberformatexception". When I type in a number I see nothing so the formatting works.

查看更多
登录 后发表回答