I want to create two or more JButton
s that share state, i.e. when the mouse button is pressed over either JButton
, both are rendered as depressed (aka "armed"), or if they are checkboxes, both are checked/unchecked simultaneously etc.
To the user, it must appear as if both buttons were the same button, appearing in more than one place in the hierarchy (in reality Swing does not allow this.)
I can get half way there by creating a single ButtonModel
and assigning the same model to both buttons. This synchronizes their armed/checked/selected states etc.
However, one noticeable effect that is not shared between buttons this way is focus - clicking on one button gives that button the focus (indicated by a rectangle within the button) and removes it from the other button. I would like to render both buttons as if they were focused whenever either button really has the focus.
Is there a clean way to do this?
Ideally I would like it to be independent of the chosen look-and-feel.
Edit: I've discovered another problem with sharing a ButtonModel
. When one of the buttons loses focus, it sets the armed
and pressed
properties of the model to false
. This happens after handling mousePressed
, so if you press the second button when the first button has focus it does not enter the pressed state until you press it a second time.