Same Jbutton selected state across multiple instances of same JPanel?

257 views Asked by At

I have a toggle JButton that, when clicked, either installs or uninstalls some listeners elsewhere (but that's somewhat irrelevant I believe, as it could be just about any code that you don't want executed any number of times in a row, hence, the toggle, you click it once, it does something, you click it again, it undoes that something or whatever). My problem is that I have several instances of this button (or more specifically, several instances of its parent JPanel). This restriction is not my doing and I cannot prevent this. Basically, I'm left with a situation where the user can toggle the button "on" a bunch of times in succession, and needless to say, this screws things up for me.

The buttons themselves are not all visible to the user at once, only one can be seen at any given time. I tried using a component listener, but componentHidden() and componentShown() are never called.

I tried making the button a singleton, but that just had this weird effect of only displaying the button on the last panel it was added to.

I'm kinda stumped. The behaviour I want is simple: Multiple instances of this toggle button that sync their selected state. Ideas?

P.S. I suppose I could construct a list of the instances and update all the other's state when one of them is clicked, but I wonder if there's something simpler out there.

Thanks

2

There are 2 answers

0
brock On BEST ANSWER

No big reveal here. I solved my problem using my own suggestion, that is, I simply kept a list of all the instances of the button and set their states when any one of them was clicked in an action they all share.

4
Hovercraft Full Of Eels On

Yes, the buttons must all be distinct, but they can either share the same ButtonModel or the same Action. Usually, I try to have them share Actions by creating a single Action that extends AbstractAction, and use it to set the Actions of all the same buttons.