Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - JButton text disappears if actionPerformed defined afterwards

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?

like image 585
Ben Avatar asked Dec 19 '11 07:12

Ben


2 Answers

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.

like image 102
MByD Avatar answered Jan 03 '23 12:01

MByD


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.

like image 38
Paul Jowett Avatar answered Jan 03 '23 13:01

Paul Jowett