Java - JButton text disappears if actionPerformed is subsequently defined

This has been undermining me for a while. If I define setTextin JButton before the definition 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 after, no problem.

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

Also, if I set the text in the JButton constructor, this is great! Yarghh!

Why is this happening?

+5
source share
5 answers

As described in the documentation:

Putting the results of an action immediately changes all the properties described in the component support component Swing.

These properties are described here and include text.

+7
source

Take a look

  private void setTextFromAction(Action a, boolean propertyChange)

AbstractButton. , setText() .

, setHideActionText(true);, .

+1

, Action . - Action, .

+1

1) EDT,

2) EDT,

3) Action Listener

0

If you want to handle the event, you do not need to Action. You can add ActionListener:

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

The call setActioncancels the predefined text.

0
source

All Articles