如何让 JFrame 在 10 秒后自行关闭?

How to make a JFrame close itself after 10 seconds?

我正在尝试制作一个在打开后 10 秒后关闭的 JFrame。

我知道你可以使用setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE),但你需要手动点击关闭框架

如果你能帮我一些代码行。

谢谢!

您可以使用 javax.swing.Timer.

Timer timer = new Timer(10000, new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
        jFrame.dispose();
    }
});
timer.setRepeats(false);
timer.start();

您可以这样使用 javax.swing.Timer:

new Timer(10_000, (e) -> { frame.setVisible(false); frame.dispose(); }).start();

使用 javax.swing.Timer 选项的优点是它不违反 Swing 线程规则。

正如 Javadocs 所说:

The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.