Optional way to close a dialog window - java

I'm using a custom JFrame to implement a simple dialog in a Java application I'm working on.
After the user pushes the 'Apply' button in the window, it should close.
What would be the most conventional way to do this? Is setVisible(false) inside the class the best way? Is there any way more recommended?

To close a window in Swing like JFrame or JDialog you have two options.
Call dispose()
Just call dispose() method:
public void dispose()
Releases all of the native screen resources used by this Window, its
subcomponents, and all of its owned children. That is, the resources
for these Components will be destroyed, any memory they consume will
be returned to the OS, and they will be marked as undisplayable.
For instance:
frame.dispose();
dialog.dispose();
Dispatch a WINDOW_CLOSING event
You can dispatch a new WindowEvent like this:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
If the window has attached a WindowListener it will be notified. If the frame's (or dialog's) default close operation is set then this action will be performed. The possible close operations are:
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 and not available for JDialog): Exit the application using the System exit method. Use this only in applications.

It depends on what you're trying to achieve. Setting the window to not visible will simply hide it but it will still be running in the background (JFrame/InternalFrame). You can use JDialog (See JOptionPane as an example) to create temporary frames which are truly closed when clicking on one of the buttons. You can also retrieve the selected option when the user closed the window (here : Javadoc). You can also forcibly close a window by firing an event to close it, like so:
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)
)
Inside an actionlistener for example.

There are multiple operations which can be performed when you close a JFrame.
Suppose you have a JFrame
JFrame frame = new JFrame();
This one exits the JVM when closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This one just hides the JFrame.
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
This one disposes the JFrame.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate
And the default is do nothing.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Related

What's the point of setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);?

I was taught to add this to always add this to the run method of jframe, but it doesn't change anything compared to not using it.
What I want to know is, what happens when you leave this out?
Thanks
#Override
public void run() {
frame = new JFrame(title);
frame.setPreferredSize(new Dimension(400, 200));
//frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
The process of your app will still remain in memory.
This is from the official documentation:
-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.
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) is used to close your JFrame as well as Java process. Test it with a JFrame sample program without the setDefaultCloseOperaton. Close your jframe by clicking the windows close. Check your task manager/top command , you will find the java process will be still running.
I know this is an old question, but what I was taught to do was create an inner class in the class that extends JFrame.
The inner class should extend WindowAdapter, and you should override the windowClosing method, I usually just put System.exit(0); in it.
Then in the constructor of your JFrame class, add this line:
this.addWindowListener(new MyWindowAdapterClass());

Second JFrame closes first

two JFrames,
JFrame Main; // Main JFrame
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
mainMenuItem.setActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try{
Sub subFrame = new Sub();
subFrame.setVisible(true);
}catch(Exception e){}
}
});
}
The problem is whenever i close the second JFrame (Sub) it closes the first aswell.
Both JFrames have:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Is that part of the problem?
EXIT_ON_CLOSE means to exit the program immediately (System.exit()) when the frame is closed.
You probably want to set this to DISPOSE_ON_CLOSE, then add a WindowListener and close the program only if both frames have been closed.
(Or, perhaps you want only the main frame to have EXIT_ON_CLOSE)
Yes. JFrame.EXIT_ON_CLOSE by definition exits the application. For your second Frame use DISPOSE_ON_CLOSE or HIDE_ON_CLOSE.
Hope this helps!
You state:
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
This suggests you've a design problem:
Your 2nd "frame" shouldn't even be a JFrame since it is not behaving as a separate independent main program window.
Instead it's acting as a dialog since it is dependent on and shown from a parent window, the main JFrame. So make the secondary window a JDialog not a JFrame, and all these problems will go away.
You will need to consider whether it should be a modal dialog where the main window is not accessable to the user while the dialog is open, or a non-modal dialog.
Having said that, you may even be better off using one window/JFrame and swapping views via a CardLayout.
Please read this link: The Use of Multiple JFrames, Good/Bad Practice?, and in particular please have a look at Andrew Thompson's community wiki answer.

JFrame and setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)

On javadoc, the HIDE_ON_CLOSE default option says that
Automatically hide the frame after invoking any registered WindowListener objects.
Now what it means "HIDE"? the realtive object is destroyed or just hide and continue using resources?
On javadoc, the HIDE_ON_CLOSE default option says that
Automatically hide the frame after invoking any registered WindowListener objects.
Now what it means "HIDE"? the realtive object is destroyed or just hide and continue using resources?
HIDE_ON_CLOSE is the same as JFrame.setVisible(false),
then JFrame in only hiden, invisible, isn't destroyed somehow (the same for JFrame.dispose()), by JFrame.setVisible(true) is again visible on the sceen and without any changes
EDIT
#giozh wrote and if i want to destroy the jframe (without close the
entire application)?
by default there isn't any reason, because by default there no reason to create another JFrame, don't do that, use CardLayout (with JFrame.pack() if is neccessary to change JFrames size on the screen)
and all those Object stays and increasing JVM memory, never will be CG'ed, then there isn't siginficant difference for JVM memory between JFrame.HIDE_ON_CLOSE, JFrame.DISPOSE_ON_CLOSE or JFrame.setVisible(false)
(in the casse that you hate CardLayout) you can to remove all JComponents from JFrames ContentPane, then to add new JComponents, set LayoutManager and last code lines (after all changes to the already visible JFrame is done) would be JFrame.(re)validate();, JFrame.repaint(); and JFrame.pack();
hide it in background without destroying it, keep it in memory
HIDE_ON_CLOSE means that it will just disppear but will be running in the background and consuming resources ,though not visible on the screen.
But using EXIT_ON_CLOSE,instead,makes it disappear as well as kills the application (Use this if you want to really close the application)

JFrame LifeCycle

Similar to start method in applet which gets called when applet window is minimized and maximized, is there some similar method which gets called when we switch control back and forth between JFrame and some other windows (such as notepad) ??
I believe your looking for WindowListener#windowActivated and WindowListener#windowdeactivated
You need to attach a listener to the frame via JFrame#addWindowListener
In Java Swing every kind of Window, including JFrame which itself extends the Window class, can listen to focus events and so can be notified when gaining or losing focus. Just call the addWindowFocusListener on your JFrame object, passing a WindowFocusListener object that will receive and deal with FocusEvents.
You can refer to the JFrame documentation for more detailed explanation.

Closing a java program properly when JDialog is the main window

I have a JDialog as the main window in my application (originally it was a JFrame but it showed in the taskbar which I didn't want).
Currently I am doing:
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
and when I click an exit button:
frame.dispose();
But the process still seems to hang around in the background
JFrame had JFrame.EXIT_ON_CLOSE which seemed to do what I wanted.
How can I close my application properly?
You need to add a WindowListener that will do System.exit(0) when the dialog closes.
JDialog dialog = ...;
dialog.addWindowListener(new WindowAdapter() {
#Override public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
Of course, the System.exit(0) after you hit the Exit button (that was suggested elsewhere in this thread) is still needed.
You can add
System.exit(0);
where you want the program to end, maybe immediately after the dispose() line.
consider using JWindow(un-decoretad by defalut), but that's little bit complicating fact, that JWindow required initializations from JFrame (just must exist, nothing else) as parent
better would be add WindowListener and all Events/Actions would be redirected/managed this way
You know that the EXIT_ON_CLOSE field is also inherited by JDialog, right?
As mentioned by #camickr, EXIT_ON_CLOSE is not a valid value for the setDefaultCloseOperation method of the JDialog class. As stated by the API,
Sets the operation that will happen by default when the user initiates
a "close" on this dialog. You must specify one of the following
choices:
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 dialog after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the dialog after invoking any registered WindowListener objects.
If EXIT_ON_CLOSE is passed as an argument, an IllegalArgumentException will be thrown.
For me worked only with windowClosing event:
dialog.addWindowListener(new WindowAdapter()
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
you can try this below amazing source code -
JDialog dialog = (JDialog) container;
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(false);
dialog.setVisible(false);
dialog.dispose();
Runtime.getRuntime().exit(1);
this above said will shut off the process as well as after disposing the JDialog container, also one more benefit is there, if this JDialog is running above any other JFrame or JDialog, so the parent will not terminate but if this JDialog is running on its own, then the process will get terminated completely, Enjoy.

Categories

Resources