Search code examples
javanulljtextfield

In Java, how can I avoid blank jtextfield input?


Due to a gui with a lot of buttons and labels, I'm using netbeans. When I test-run it in netbeans, if I leave the jtextfield blank and submit it, I get:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1

I was looking at the jbutton I am using to submit the data and although I can see the following field, I cannot edit it:

        butSub.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            butSubActionPerformed(evt);
        }
    });

I thought maybe in that I could run an if or a try/catch block, but again it won't let me edit it. If the user inputs nothing, I want it to tell them so and then return to the start.


Solution

  • You are trying to edit IDE generated code. Don't do that. Instead edit the code in butSubActionPerformed() which is being called by the ActionListener. You can check if the text field is empty using:

    if(jTextField.getText().isEmpty()){
        //error
    } else //every thing is fine, you can continue.
    

    Again, this code has to be in the method being called by the ActionListener.