要在按钮上设置延迟,请单击java?

Anu*_*dha 4 java concurrency swing timer

我有一个保存按钮JFrame;点击时将"保存"文本设置保存为"保存...."; 我需要在延迟10秒后将该文本设置为"已保存".如何在Java中实现?请帮忙...

try {
    Thread.sleep(4000);
} catch (InterruptedException e) {

    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

这就是我所做的......但是在这段延迟的时间里,这不会表现为"拯救".

And*_*son 7

这个问题和前3个答案正走向错误的轨道.

  • 使用a JProgressBar来显示正在发生的事情.如果任务的长度未知,则将其设置为不确定,但可能您知道需要保存多少以及当前保存了多少.
  • 不要阻止EDT(事件调度线程) - 当发生这种情况时,GUI将"冻结".使用SwingWorker长时间运行的任务.有关更多详细信息,请参阅Swing中的并发.


Ano*_*ous 6

如果你想为用户提供视觉反馈的东西是怎么回事用户(可能提供有关进展情况有些淡淡的),然后去JProgressBarSwingWorker(更多详细信息).

另一方面,如果您想要出现这种情况,当用户单击该按钮并且该任务应该在后台运行时(当用户执行其他操作时),那么我将使用以下方法:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {                                          
        button.setEnabled(false); // change text if you want
        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                // Do the calculations
                // Wait if you want
                Thread.sleep(1000);
                // Dont touch the UI
                return null;
            }
            @Override
            protected void done() {
                try {
                    get();
                } catch (Exception ignore) {
                } finally {
                    button.setEnabled(true); // restore the text if needed
                }
            }                    
        }.execute();
    }
});
Run Code Online (Sandbox Code Playgroud)

最后,使用Swing特定计时器的初始解决方案:

final JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {                                          
        // Take somehow care of multiple clicks
        button.setText("Saving...");
        final Timer t = new Timer(10000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                button.setText("Saved");
            }
        });
        t.setRepeats(false);
        t.start();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • *"回答**特定问题的最佳选择**.."*最好的选择是指出这是一种错误思考的方法.您可能已经从我的回答中注意到(我的意见).;) (2认同)