Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent to close Java swing Application

Tags:

windows

swing

How to prevent to close Java swing Application, when user clicks on close button?

like image 816
SamSol Avatar asked May 28 '10 13:05

SamSol


People also ask

How do I stop a JFrame from closing?

To disable the close operation on a JFrame , when user click the close icon on the JFrame , we can set the value of the default close operation to WindowConstants. DO_NOTHING_ON_CLOSE .

How do you pause a swing in Java?

In Java, we can use TimeUnit. SECONDS. sleep() or Thread. sleep() to pause a program for a few seconds.

Which method is used to close a swing frame in Java?

We can close the AWT Window or Frame by calling dispose() or System. exit() inside windowClosing() method.

What is replacing Java Swing?

Hint: Oracle has developed JavaFX to replace both Swing and AWT. Since Java SE 7, update 6 it is bundled with Java SE. "JavaFX is a set of graphics and media packages that enables developers to (...) deploy rich client applications that operate consistently across diverse platforms" [1].


2 Answers

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); on your main frame should prevent that.

The setDefaultCloseOperation(int) method allows you to choose what to do when the user closes the JFrame:

  • DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.

  • HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.

  • DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.

  • EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

like image 152
Gnoupi Avatar answered Oct 23 '22 16:10

Gnoupi


JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

frame.addWindowListener(new WindowAdapter() {
// handle window closing 
});
like image 2
PeterMmm Avatar answered Oct 23 '22 16:10

PeterMmm