Reputation: 57267
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?
Upvotes: 4
Views: 3278
Reputation: 354
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.
Upvotes: 0
Reputation: 137372
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.
Upvotes: 6
Reputation: 109813
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
setText()
invoke javax.swing.Timer with Action that provide rest of events inside your original ActionListener
Upvotes: 0
Reputation: 9317
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.
Upvotes: 1
Reputation: 6581
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.
Upvotes: 1