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

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());

Related

Optional way to close a dialog window

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);

Bringing specific Jdialog to front when having multiple jdialogs in one application

I have multiple JDialogs in my application stored in a map. These JDialogs are all have
setModel(false);
When these dialogs are out of focus and I want to bring a specific JDialog toFront all JDialogs come toFront. I want the specific Jdialog to come to front and want the other JDialogs to remain in back.
HashMap<String, JDialog> jDialogMap = getJDialogMap();
String key = "jd1";
JDialog specificJDialog= jDialogMap.get(key);
if (specificJDialog== null){
specificJDialog= new JDialog();
specificJDialog.setModel(false);
specificJDialog.setVisible(true);
jDialogMap.put("jd2", specificJDialog);
} else {
specificJDialog.toFront();
return;
}
This code brings all the JDialogs toFront having the specificJDialog on top of the stack.
getJDialogMap();
This Method only returns a HashMap nothing else.
use requiredDialogObject.requestFocusInWindow();
whenever u need focus on the specific dialog
I found a solution to my problem I think it is worth sharing it.
Solution: Creating multiple JDilogs in an application with default constructor i.e. new JDialog() will result in a shared frame as the parent of each JDialog which will cause these kind of problems. So I used the overloaded constructor new JDialog(new JFrame()) to have separate parent for each JDialog and that solved my problem.
Had a similar issue. After opening the JDialog my main application window just requested the focus again, moving the JDialog window to the background, which was annoying. I experimented with modal() and toFront() methods, which both didn't work out for me, since modal() just prevented user interaction completely (outside of that JDialog) and toFront() also has effect on windows outside my application (by using it inside of a timer method, see below).
To keep the window in front of the main application I used a timer method, which was fired every 300 ms and just keeps requesting the focus by using the requestFocus() method.
import javax.swing.Timer;
Timer timer = new Timer(300, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
requestFocus();
}
});
timer.start();

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.

How do I make a button in a Java Applet that opens a JFrame?

I've made a few JFrames and I want to call them from a JApplet. What is the best way to do this? Could I just instantiate my JFrames in my init method and then call them whenever a button is pushed?
How do I make a button in a Java Applet that opens a JFrame?
You probably shouldn't do this, but rather if you want to open another window from the JApplet, create and show a JDialog. They are created and displayed similar to a JFrame, but uses different constructors. You will need to get the applet's Window for the "owner" parameter of the JDialog, and this can be obtained via:
Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, comp);
Where comp is a visible component in the JApplet.
Ok, it sounds like you initialize a JFrame on initialization and you store it. You don't need to re-instantiate the JFrame from initalization. Instead just store it in a field of your Applet and use it when ever the button is pressed.
OR you can use Singletons and lazy initialization:
class JFrameToOpen extends JFrame {
private static JFrame frame = null;
private JFrameToOpen() {
//init
}
public static GetJFrame() {
if(frame==null) {
frame=new JFrameToOpen();
}
return frame;
}
}
But singletons are ugly and many people choose to avoid them.
You can just create JFrame with its default constructor and then show it:
JFrame frame = new JFrame();
JLabel label = new JLabel("Welcome");
frame.add(label);
frame.pack();
frame.setVisible(true);
This code forks from the applet similar way as from the standalone program. No need for any special tricks. The applet itself then can only contain buttons like "press to launch the application".

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