Program a button to press at most once every 5 seconds in java

For the current project, we only need to allow the user to press the button once every 5 or so seconds. We use the button to start the print job, but we need to stop users from the spam button and start a dozen print jobs.

We are currently trying to use the following code, but it seems to push the buttons even when the button is disabled. Therefore, after a 5-second delay, clicks are recorded even hard at this time when the button is disabled.

private void Button1ActionPerformed(java.awt.event.ActionEvent evt) { Button1.setEnabled(false); pressCount++; System.out.println("Press count: " + pressCount); PrintJob print = new PrintJob(); try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex); } try { print.PrintJob(); } catch (IOException ex) { Logger.getLogger(GUIFrame.class.getName()).log(Level.SEVERE, null, ex); } } 
+4
source share
2 answers

Program a button to press at most once every 5 seconds in java

+3
source

Do not press EDT for 5 seconds. You must use another thread to sleep for 5 seconds, and the button setting has been activated. Something like that:

 new Thread(new Runnable() { public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // handle it } SwingUtilities.invokeLater(new Runnable() { public void run() { Button1.setEnabled(true); } }); } }).start(); 
+3
source

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


All Articles