我可以在Java Swing JDialog框上设置一个计时器,以便在几毫秒后关闭

Dav*_*ave 10 java swing timer scheduler jdialog

您可以创建一个Java Swing JDialog框(或替代Swing对象类型),我可以使用它来提醒用户某个事件,然后在延迟后自动关闭对话框; 不必关闭对话的用户?

Ste*_*eod 14

此解决方案基于oxbow_lakes',但它使用javax.swing.Timer,适用于此类事物.它总是在事件派发线程上执行其代码.这对于避免细微但令人讨厌的错误非常重要

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        final JDialog dialog = new JDialog(f, "Test", true);
        Timer timer = new Timer(2000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        timer.setRepeats(false);
        timer.start();

        dialog.setVisible(true); // if modal, application will pause here

        System.out.println("Dialog closed");
    }
}
Run Code Online (Sandbox Code Playgroud)


oxb*_*kes 7

是的 - 当然可以.你试过安排结束吗?

JFrame f = new JFrame();
final JDialog dialog = new JDialog(f, "Test", true);

//Must schedule the close before the dialog becomes visible
ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();     
s.schedule(new Runnable() {
    public void run() {
        dialog.setVisible(false); //should be invoked on the EDT
        dialog.dispose();
    }
}, 20, TimeUnit.SECONDS);

 dialog.setVisible(true); // if modal, application will pause here

 System.out.println("Dialog closed");
Run Code Online (Sandbox Code Playgroud)

上述程序将在20秒后关闭对话框,您将看到打印到控制台的文本"Dialog closed"

  • 您应该在事件派发线程上调用dialog.setVisisble(false).否则代码行为是不可预测的. (2认同)