Disable button on click before actionPerformed completed java

I have a button that performs a long function, I want to disable this button after the user once clicks on it so that he cannot click it again

The button is disabled, but the problem is that after the function is completed, the button is activated again

I tried to put button.setEnabled(false); to a new stream, but it did not work.

to test this sample 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++) { } } } } }); 
+4
source share
3 answers

Use SwingWorker for lengthy background tasks. In this example, the startButton action has setEnabled(false) , and the implementation is done() < done() .

+5
source
  • all wrapped in public void actionPerformed(ActionEvent ae) { are executed at one time (on the screen) when all lines of code are executed, this is the main rule for AWT / Swing Listeners and EventDispatchThread

  • you need to delay the event in EDT using

    • Short delay with swing timer
    • redirect the rest of the code (after button.setEnabled(false); ) to SwingWorker , the easiest way is to Runnable#Thread , mark all output from Runnable#Thread to the already visible Swing GUI, which should be enclosed in invokeLater
  • the correct paths will use only Swing Action and instead of blocking JButton set Action.setEnabled(false) only

+2
source

Edit: It is tempting to think that you can use a mouse listener to implement this. For example, so that you cannot use the event emitted by the mouse, or the mouse click event that the mouse listens to. Inside you can write button.setEnable(false) . Unfortunately, this also blocks the flow of sending events .

+1
source

Source: https://habr.com/ru/post/1492922/


All Articles