Said
Said

Reputation: 197

Can not check whether a JButton is clicked using NetBeans

I am trying to create a JForm using NetBeans's Design mode and then developing it in Source mode. I have two buttons in my form and I want to check whether the generateNumber button is clicked or not before the makeGuess button performs its task. Here are the related code lines.

private void generateNumberActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:

    }                                              

    private void makeGuessActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:

        try {
            if (!generateNumber.getModel().isPressed()) {
                throw new GameNotStartedException();
            }
        } catch (GameNotStartedException ex) {
            System.out.println(ex);
            JOptionPane.showMessageDialog(this, "Generate a number first");
        }

    }

My problem is the program always falls into the GameNotStartedException, not matter if I click to generateNumber button or I do not. Can anyone help me, please?

Upvotes: 0

Views: 152

Answers (1)

Stefan Freitag
Stefan Freitag

Reputation: 3608

I think the problem is the usage of generateNumber.getModel().isPressed() itself. This tells you if the button is currently pressed or not.

As you have it in the method makeGuessActionPerformed it is like this:

  • You are pressing the button makeGuess
  • The method makeGuessActionPerformed is executed
  • As part of the method you check if button generateNumber is clicked (which is not true, as you clicked on button makeGuess)

You could e.g. use a boolean value to keep track of the status. The value of the boolean reflects if the button generateNumbers was already pressed.

  • A click on the button generateNumbers sets the boolean value to true.
  • In the method makeGuessActionPerformed you can check for the value of the boolean. If false, then throw the exception. Otherwise continue with your execution.

Upvotes: 1

Related Questions