Disable button on click before actionPerformed is completed java

痞子三分冷 提交于 2019-12-22 09:27:26

问题


I have a button doing a long function, I want to disable this button after the user once click on it to in order to prevent him from clicking it again many times

The button gets disabled but the problem is after the function finished the button gets enabled again
i tried to put button.setEnabled(false); in a new thread but it didn't work either

for testing this sample of code

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        button.setEnabled(false);
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < Integer.MAX_VALUE; j++) {
                for (int ii = 0; ii < Integer.MAX_VALUE; ii++) {
                }
            }
        }
    }
});

回答1:


Use SwingWorker for long running background tasks. In this example, the startButton action does setEnabled(false), and the worker's done() implementation does setEnabled(true).




回答2:


  • everything wrapped in public void actionPerformed(ActionEvent ae) { is done at one moment, (on the screen) when all code lines are executed, this is basic rule for AWT/Swing Listeners and EventDispatchThread

  • you need to delay event in EDT by using

    1. short delay with Swing Timer,
    2. redirect rest of code (after button.setEnabled(false);) to SwingWorker, easiest to Runnable#Thread, note all output from Runnable#Thread to the already visible Swing GUI must be wrapped into invokeLater
  • proper of ways will be only using Swing Action and instead of locking the JButton to set Action.setEnabled(false) only




回答3:


Edit: It's tempting to think you could use a mouse listener to implement this. For example, to prevent you could use mouse released event or mouse clicked event of mouse listener. Inside that you could write button.setEnable(false). Unfortunately, this also blocks the event dispatch thread.



来源:https://stackoverflow.com/questions/17807846/disable-button-on-click-before-actionperformed-is-completed-java

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