3

I'm writing a simple Swing app. I tried adding a checkbox as listed below. Once I added the actionHandler loadPickers the name Foo disappeared from where it was sitting next to the right of chckbxNewCheckBox. I tried adding a call to setHideActionText(), but now nothing displays.

JCheckBox chckbxNewCheckBox = new JCheckBox("Foo");
chckbxNewCheckBox.setToolTipText("");
chckbxNewCheckBox.setName("");
chckbxNewCheckBox.setHideActionText(true);
chckbxNewCheckBox.setAction(loadPickers);
mainPanel.add(chckbxNewCheckBox, "flowy,cell 0 1");

If I change it to this it works properly. I see the text "Foo".

JCheckBox chckbxNewCheckBox = new JCheckBox("Foo");
chckbxNewCheckBox.setToolTipText("");
chckbxNewCheckBox.setName("");
chckbxNewCheckBox.setHideActionText(true);
chckbxNewCheckBox.setAction(loadPickers);
chckbxNewCheckBox.setText("Foo"); //THIS DOES NOT WORK IF IT COMES BEFORE SET ACTION
mainPanel.add(chckbxNewCheckBox, "flowy,cell 0 1");

I've included the action here for completeness. Why does it work this way? Am I missing something here? Currently I'm using the WindowBuilder plugin for Eclipse with the Mig layout system (which I really like). Unfortunately I haven't figure out if there's a way to make WindowBuilder use the .setText() method instead of using the constructor. Any help on what I'm doing wrong, any insight on why this behavior exists like this, or a good workaround for WindowBuilder would be great.

private class LoadPickers extends AbstractAction {
    public LoadPickers() {
        //putValue(NAME, "SwingAction_2");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jazzepi
  • 5,259
  • 11
  • 55
  • 81

1 Answers1

5

As explained in the JavaDoc of AbstractButton.setAction:

Setting the Action results in immediately changing all the properties described in Swing Components Supporting Action. Subsequently, the button's properties are automatically updated as the Action's properties change.

So all the following properties can be impacted by setting an action:

  • enabled
  • toolTipText
  • actionCommand
  • mnemonic
  • text
  • displayedMnemonicIndex
  • icon (NA for JCheckBox)
  • accelerator (NA for JCheckBox)
  • selected
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • Thanks for the answer! I guess I don't really understand the point of having the text for the action either over-write or null out the text value of the button it's being applied to. I have a single action handler that is agnostic to which checkbox is clicked, so I want to register all my checkboxes with that single action handler. In this case I have to do a bunch of extra legwork unless I make three separate action handlers for each button. It seems like inherenting the values from the action handler discourages reuse of these action handlers? – Jazzepi Jul 16 '12 at 12:46