首页 > 解决方案 > 单击按钮时如何延迟程序(java swing)

问题描述

我正在创建一个带有 ajbutton和 a的程序jtextfield。我希望文本字段显示一条消息,然后在 1 秒后使整个帧消失。我能够显示消息并使框架消失,frame.dispose但我看不到消息,因为框架立即消失。这是我尝试过的。我听说使用摇摆定时器也可以,但我不知道如何使用摇摆定时器。

//imports

public class GUIFastCash {

    JFrame frame;
    static JTextField window;
    JButton twenty;

    public void go () {
        window = new JTextField();
        twenty = new JButton("$20");
        twenty.addActionListener(new Twenty());

        frame = new JFrame();
        //code adding button and textfield to frame
    }

    class Twenty implements ActionListener {
        public void actionPerformed (ActionEvent event) {
            //code to execute

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            frame.dispose();

        }
    }

}

标签: javaeclipseswingdelay

解决方案


首先是创建 TimerTask 的子类并覆盖 run 方法。然后,将计时器设置为在设定的时间后运行。

class Dispose extends TimerTask {
    @Override
    public void run() {
        frame.dispose;
    }
}

然后...

new Timer().schedule(new Dispose(), 1000);

计时器对象将在 1000 毫秒 (1s) 后处理帧


推荐阅读