-1

I am trying to make a JFrame that closes after 10 seconds after openning.

I know that you can use setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) , but you need to manually click to close the frame.

If you could help me with some codelines.

Thanks!

camickr
  • 321,443
  • 19
  • 166
  • 288

2 Answers2

2

You can use javax.swing.Timer.

Timer timer = new Timer(10000, new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
        jFrame.dispose();
    }
});
timer.setRepeats(false);
timer.start();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

You could use javax.swing.Timer like this:

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

The advantage of using the javax.swing.Timer option is that it doesn't violate Swing threading rules.

As the Javadocs say:

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.

AminM
  • 822
  • 4
  • 11