HunderingThooves
HunderingThooves

Reputation: 992

Java swing, test state of a button?

I am trying to write a method that will toggle a button from being disabled to being enabled and back using a simple if statement.

I would assume that it would be something like

if (buttonDisable.setEnabled(true) == true){
    //do stuff
}

But I haven't had much luck finding my answer via google.

Upvotes: 2

Views: 735

Answers (2)

Edwin Buck
Edwin Buck

Reputation: 70909

Don't test the display of the model, test the model.

if (buttonDisable.getModel().isEnabled()) {
  // do stuff
}

That way if you change the model, you avoid a level of dispatch (view --- updates ---> model --- updates ---> view(s))

A better solution is to make your model changes independent of the view. This way you don't get tied into requiring a specific view to be present to make the model change.

ButtonModel toggle = new ButtonModel();
...
JButton button = new JButton(toggle);
...
// this is clear that we are manipulating the model, not the view
// as new views are added / removed, this toggle will continue to work
toggle.setEnabled(!toggle.isEnabled());

Upvotes: 4

Reverend Gonzo
Reverend Gonzo

Reputation: 40821

Why not just toggle the state in one shot:

buttonDisable.setEnabled(!buttonDisable.isEnabled())

Upvotes: 4

Related Questions