For input string: “” when textfields are filled out

寵の児 提交于 2019-12-11 17:51:06

问题


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:


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.



来源:https://stackoverflow.com/questions/16471729/for-input-string-when-textfields-are-filled-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!