要在java中设置单击按钮的延迟? [英] To set delay on a button click in java?

查看:700
本文介绍了要在java中设置单击按钮的延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JFrame 中有一个保存按钮;点击将保存文本集保存到保存....;我需要将该文本设置为保存经过10秒的延迟。在Java中是可能的吗?
请帮助...

I have a save button in a JFrame ;on clicking save the 'save' text sets to 'saving....'; I need to set that text as 'saved' after a delay of 10 seconds.How is it possible in java? Please help...

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

    e.printStackTrace();
}

这是我做的...但这不会显示为在该延迟时间期间。

This is what i did...but this wont shows as 'saving' during that delayed time.

推荐答案

如果您想向用户提供视觉反馈,以了解进度(可能给出一些进度提示)然后访问 JProgressBar SwingWorker 更多详情

If you want to provide the user with visual feedback that something is going on (and maybe give some hint about the progress) then go for JProgressBar and SwingWorker (more details).

如果在另一方面,你想有一种情况,当用户点击按钮,而任务应该在后台运行(而用户做其他事情),那么我将使用以下方法:

If on the other hand you want to have a situation, when user clicks the button and the task is supposed to run in the background (while the user does other things), then I would use the following approach:

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();
    }
});

最后,使用 Swing 特定计时器

Finally, the initial solution that was using the Swing specific timer:

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();
    }
});

这篇关于要在java中设置单击按钮的延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆