如何在按钮单击之间创建延迟(以防止按钮垃圾邮件)



我正在创建一个java程序,它涉及一个按钮,该按钮会产生一堆问题。我想知道如何在用户可以单击按钮的时间之间创建延迟(以防止按钮垃圾邮件)。这是我尝试过的。

public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Thread DelayTHREAD = new Delay();
    if(DelayTHREAD.isAlive()) {
        /*do nothing*/
    }
    else {
        /*some other code*/
        DelayTHREAD.start();
    }
}
public static class Delay extends Thread /*Prevents user from spamming buttons*/ {
    @Override
    public void run() {
        try {
            Thread.sleep(5000); /*sleeps for the desired delay time*/
        }catch(InterruptedException e){
        }
    }
}

好的,这就是问题所在,延迟线程是否启动并不重要,程序仍然会继续并继续执行执行的操作,就好像延迟线程甚至不存在一样。

有人请告诉我如何创建延迟,以便用户无法在程序中发送垃圾邮件按钮?谢谢:)

您可以创建一个小方法,在用户单击按钮后的一段时间内禁用该按钮,然后在之后启用它,如下所示:

static void disable(final AbstractButton b, final long ms) {
    b.setEnabled(false);
    new SwingWorker() {
        @Override protected Object doInBackground() throws Exception {
            Thread.sleep(ms);
            return null;
        }
        @Override protected void done() {
            b.setEnabled(true);
        }
    }.execute();
}

然后从 actionPerforming 方法调用它,如下所示:

disable(button, 5000);

只需确保从 EDT 调用它即可。

使用SwingTimer在按钮单击和激活关联操作之间注入延迟。

import javax.swing.Timer;
/*...*/
private Timer attackTimer;
/*...*/
attackTimer = new Timer(5000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        // Do attack...
    }
});
attackTimer.setRepeats(false);
/*...*/
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // Restart the timer each time the button is clicked...
    // In fact, I would disable the button here and re-enable it
    // in the timer actionPerformed method...
    attackTimer.restart();
}

最新更新