Java - JButton text disappears if actionPerformed defined afterwards

北城以北 提交于 2019-12-10 15:27:15

问题


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:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/8558235/java-jbutton-text-disappears-if-actionperformed-defined-afterwards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!