peter55555
peter55555

Reputation: 1475

Enabled/Disabled JButton associated with some method

I'd like to have JButton in some class that is enabled/disabled when some method returns true/false (method return component of class - type boolean)

I don't know how to do that. Should I write instruction while(true) { ... } and check what method returns for example 1 per second? Is it a good idea?

Please help

Upvotes: 0

Views: 280

Answers (3)

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

Should I write instruction while(true) { ... } and check what method returns for example 1 per second? Is it a good idea?

This is bad idea, it will freeze your application completely! If you want to check the value of boolean method periodically use the Timer.

However if the boolean method is defined in say Object A and you know when A is modified then you should add the buttons as listener to A so that when A is modified it can trigger a callback in the Button which will evaluate whether the button should be enabled or disabled now.

Upvotes: 1

SamYan
SamYan

Reputation: 1571

final JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        btnNewButton.setEnabled(buttonState());
    }
});

boolean buttonState() {
    return false;
}

Upvotes: 0

Levenal
Levenal

Reputation: 3806

enter image description here

From Java Se 7 Doc,

Methods inherited from class javax.swing.AbstractButton

If you put this code within your method, then whenever it runs, it will enable/disable the button accordingly.

Upvotes: 1

Related Questions