5

This has been bugging me for a while. If I define setText on a JButton before defining setAction, the text disappears:

JButton test = new JButton();
test.setText("test");  // Before - disappears!
test.setAction(new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});
this.add(test);

If it's after, no problems.

JButton test = new JButton();
test.setAction(new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});
test.setText("test");  // After - no problem!
this.add(test);

Furthermore, if I set the text in the JButton constructor, it's fine! Yarghh!

Why does this happen?

1
  • Thanks fellas, +1s all around. 7 minutes to go.
    – Ben
    Dec 19, 2011 at 7:28

5 Answers 5

7

As described in the documentation:

Setting the Action results in immediately changing all the properties described in Swing Components Supporting Action.

Those properties are described here, and include text.

1
  • Fastest gun in the west...and with documentation too.
    – Ben
    Dec 19, 2011 at 7:36
1

Have a look at

  private void setTextFromAction(Action a, boolean propertyChange)

in AbstractButton. You can see it's calling setText() based on the action.

It looks like you can call setHideActionText(true); to sort out your problem.

1
  • docs.oracle.com/javase/7/docs/api/javax/swing/… I am calling setHideActionText(true) before setting the action but it is not working, the text is still empty. To solve this I simply saved the text in a temporary variable and set it back after setting the action...not fancy but it works. Any suggestion to write better code is welcome. Jul 2, 2012 at 12:34
1

This is because Action has name for the control as well. Since you are not setting any name in the Action it is getting set to empty string.

0

1) Listeners put all Events to the EDT,

2) all events are waiting in EDT and output to the screen would be done in one moment

3) you have to split that to the two separate Action inside Listener

0
0

If you only want to handle the event, you don't need Action. You can add an ActionListener:

JButton test = new JButton();
test.setText("test");  
test.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});
this.add(test);

Calling setAction overrides pre-set text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.