JFrame Exit on close Java - java

I don't get how can I employ this code:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to close the program with the x button.

You need the line
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Because the default behaviour for the JFrame when you press the X button is the equivalent to
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
So almost all the times you'll need to add that line manually when creating your JFrame
I am currently referring to constants in WindowConstants like WindowConstants.EXIT_ON_CLOSE instead of the same constants declared directly in JFrame as the prior reflect better the intent.

If you don't have it, the JFrame will just be disposed. The frame will close, but the app will continue to run.

Calling setDefaultCloseOperation(EXIT_ON_CLOSE) does exactly this. It causes the application to exit when the application receives a close window event from the operating system. Pressing the close (X) button on your window causes the operating system to generate a close window event and send it to your Java application. The close window event is processed by the AWT event loop in your Java application which will exit the application in response to the event.
If you do not call this method the AWT event loop may not exit the application in response to the close window event but leave it running in the background.

I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.
I finally ended with:
Do not use EXIT_ON_CLOSE as this can leave resources behind;
Do use something like the following in the JFrame initialization:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame() returns a reference to the JFrame:
public class AppMenuFileExit extends JMenuItem implements ActionListener
{
// do your normal menu item code here
#Override
public void actionPerformed(ActionEvent e)
{
WindowEvent we;
we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
App.getFrame().dispatchEvent(we);
}
}
JFrame is a subclass of Window so may be cast to Window for this purpose.
And, have the following in your JFrame class to handle Window messages:
public class AppFrame extends JFrame implements WindowListener
{
// Do all the things you need to for the class
#Override
public void windowOpened(WindowEvent e)
{}
#Override
public void windowClosing(WindowEvent e)
{/* can do cleanup here if necessary */}
#Override
public void windowClosed(WindowEvent e)
{
dispose();
System.exit(0);
}
#Override
public void windowActivated(WindowEvent e)
{}
#Override
public void windowDeactivated(WindowEvent e)
{}
#Override
public void windowDeiconified(WindowEvent e)
{}
#Override
public void windowIconified(WindowEvent e)
{}
}

If you're using a Frame (Class Extends Frame) you'll not get the
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

If you don't extend JFrame and use JFrame itself in variable, you can use:
frame.dispose();
System.exit(0);

The following code works for me:
System.exit(home.EXIT_ON_CLOSE);

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this worked for me in case of Class Extends Frame

Related

How do I call the JFrame (the class itself) inside a windowslistener method?

I want to reference the JFrame (which is the class itself) inside a WindowsListener method. Is there any way to do this?
diag_ap.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
this.setEnabled(true); //does not work
}
});
I expect to call the class frame and disable it so that the only thing that can be pressed is the JDialog box.
Using this keyword inside new WindowAdapter().windowClosing(event) method refers to the WindowAdapter object that you created.
To refer the object of the JFrame inside WindowAdapter, you should use MyJFrame.this. So, the code should be,
diag_ap.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
MyJFrame.this.setEnabled(true); // replace MyJFrame with name of your JFrame
}
});

How to close JInternalFrame by pressing escape key?

I created one JFrame with JDesktopPane, in which I am calling JInternalFrame. Now I want to close that internal frame by pressing escape key.
I tried 2-3 ways, but no output.
I did that by using code given below:
public static void closeWindow(JInternalFrame ji){
ActionListener close=New ActionListener(){
public void actionPerformed(ActionEvent e){
ji.dispose();
}
};
When I called above method from my intern frame class constructor by supplying its object , I was able to close it. But when there I write some other lines of code to the constructor. The above method call doesn't work. Please help me. I unable to find the problem in the code.
Also I tried to add KeyListener to internal frame, so I able to work with key strokes,but it also doesn't work.
Again I tried to setMnemonic to button as escape as below:
jButton1.setMnemonic(KeyEvent.VK_ESCAPE);
But also gives no output.
You need to implement the KeyListener interface, or add one that is Anonymous. In this example, I just implemented it.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class JInternalFrame extends JFrame implements KeyListener {
public JInternalFrame()
{
super();
// other stuff to add to frame
this.setSize(400, 400);
this.setVisible(true);
this.addKeyListener( this );
}
#Override
public void keyTyped(KeyEvent e) {
// Don't need to implement this
}
#Override
public void keyPressed(KeyEvent e) {
if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
System.exit(0); //Change this to dispose or whatever you want to do with the frame
}
}
#Override
public void keyReleased(KeyEvent e) {
//Dont need to implement anything here
}
public static void main(String[] args)
{
JInternalFrame frame = new JInternalFrame();
}
}
Now if this is an internal jframe as mentioned, it is probably better to implement the keylistener in the JDesktopPane and call the dispose method on the JInternalFrame after pressing escape instead of implementing keylistener in this frame. It all depends on which GUI component has focus of input.
This issue is old now but I recently got stuck on a similar problem. Adding the key listener to the content pane of the internal frame instead of the internal frame itself did the job for me.
this.getContentPane().addKeyListener(this);

How to perform action after JFrame is closed?

I need to perform an action after the JFrame is closed and I have this part of code for it, but this doesn't work.
Could anyone please advise what should be change here?
private void changeDefaults(){
Thread changeDefaultsThread = new Thread(new Runnable(){
public void run(){
Change ch = new Change();
ch.setVisible(true);
ch.setListeners();
ch.defaultInput();
while(ch.isActive()){
System.out.println("active");
}
updateDefaults();
}
});
changeDefaultsThread.start();
}
Change is the JFrame I am opening for another action.
You can add listener to your JFrame
frame.addWindowListener (new java.awt.event.WindowAdapter)
and override the windowClosing
#Override
public void windowClosing
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
//do something
}
});
I'm surprised no one has mentioned the simplest solution: don't use a JFrame. The best tool for this behavior -- displaying a child window and doing something immediately after it has closed -- is to use a modal dialog window such as a JDialog or JOptionPane. The JDialog set up code is very similar to that of the JFrame, with an exception being that it uses different constructors, and should have the parent window passed into it, and it uses a subset of the default close operations.
If you use a modal dialog, then program flow is halted in the calling code immediately after the dialog has been displayed (think of how a JOptionPane operates), and then immediately resumes from the spot after calling setVisible(true) on the dialog once the dialog has been closed.
The only bugaboo is that if you don't want modal behavior -- if you don't want the parent/calling window to be disabled while the child window is displayed -- then you'll have to use a non-modal JDialog window with a WindowListener.
If you want to perform an action when closing a JFrame, you just need to attach a WindowListener (extending WindowAdapter so that you do not need to implement all WindowListener methods):
import javax.swing.*;
public class AfterJFrameClose {
public static void main(String[] args) {
JFrame frame = new JFrame("My frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.out.println("Frame closing");
}
});
}
}
Instead of the System.out.println, just write the code you want to have executed.
Update: If you want to access another frame, you either should pass it as a parameter as suggested above or you can also iterate through active frames using something like this:
Frame[] frames = Frame.getFrames();
for (Frame frame: frames) {
System.out.println(frame.getTitle());
}

JFrame question

What code is called when a JFrame is minimized? Is it hooked up to a listener? I just want to know what happens internally when the frame is minimized.
EDIT:
Im actually looking for the code that is called when the frame is minimized. For example, the code for the actual windowListener. Ive been searching through JFrame, Frame, and Window searching for windowIconified but have been unable to find the actual code.
Reason being, when my program runs, it has a small defect with one of the Panels, but when I minimize and maximize the JFrame, the problem goes away. I wanted to see what was going on so that I can apply whatever is going on to my Panel so it paints right.
you can listening by using WindowListener
for example
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class WinStateListener implements WindowListener {
static JFrame window = new JFrame("Window State Listener");
public WinStateListener() {
window.setBounds(30, 30, 300, 300);
window.addWindowListener(this);
window.setVisible(true);
}
public static void main(String[] args) {
WinStateListener winStateListener = new WinStateListener();
}
public void windowClosing(WindowEvent e) {
System.out.println("Closing");
window.dispose();
System.exit(0);
}
public void windowOpened(WindowEvent e) {
System.out.println("Opened");
}
public void windowClosed(WindowEvent e) {
System.out.println("Closed");
}
public void windowIconified(WindowEvent e) {
System.out.println("Iconified");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Deiconified");
}
public void windowActivated(WindowEvent e) {
System.out.println("Activated");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Deactivated");
}
}
You want to read about WindowListeners and WindowEvents. The event you are talking about is called Iconifying the window. Read more here:
http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html
EDIT:
Use revalidate() then repaint() on the JPanel that is acting up.
When minimizing the JFrame application a window event windowIconified is called. If you want to process such window events by your own then either implement WindowListener interface or use WindowAdapter abstract class.
What code is called when a JFrame is minimized?
As noted in How to Make Frames: Specifying Window Decorations, "window decorations are supplied by the native window system." The article goes on to describe some changes you can make to the host platform's default.
Addendum: Reading your update, note that restoring an iconified window repaints it. As #Andrew Thompson points out, you may need to verify that you're building on the event dispatch thread. You may also need to schedule a repaint(). An sscce might clarify things.

How to programmatically close a JFrame

What's the correct way to get a JFrame to close, the same as if the user had hit the X close button, or pressed Alt+F4 (on Windows)?
I have my default close operation set the way I want, via:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
It does exactly what I want with the aforementioned controls. This question isn't about that.
What I really want to do is cause the GUI to behave in the same way as a press of X close button would cause it to behave.
Suppose I were to extend WindowAdaptor and then add an instance of my adaptor as a listener via addWindowListener(). I would like to see the same sequence of calls through windowDeactivated(), windowClosing(), and windowClosed() as would occur with the X close button. Not so much tearing up the window as telling it to tear itself up, so to speak.
If you want the GUI to behave as if you clicked the X close button then you need to dispatch a window closing event to the Window. The ExitAction from Closing An Application allows you to add this functionality to a menu item or any component that uses Actions easily.
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
Not too tricky.
If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...) will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.
If by Alt-F4 or X you mean hide the window, then frame.setVisible(false) is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.
If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose() is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).
dispose() might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?
The Java Swing Tutorial on Window Listeners may help clarify things for you.
Stop the program:
System.exit(0);
Close the window:
frame.dispose();
Hide the window:
frame.setVisible(false);
If you have done this to make sure the user can't close the window:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Then you should change your pullThePlug() method to be
public void pullThePlug() {
// this will make sure WindowListener.windowClosing() et al. will be called.
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
// this will hide and dispose the frame, so that the application quits by
// itself if there is nothing else around.
setVisible(false);
dispose();
// if you have other similar frames around, you should dispose them, too.
// finally, call this to really exit.
// i/o libraries such as WiiRemoteJ need this.
// also, this is what swing does for JFrame.EXIT_ON_CLOSE
System.exit(0);
}
I found this to be the only way that plays nice with the WindowListener and JFrame.DO_NOTHING_ON_CLOSE.
Exiting from Java running process is very easy, basically you need to do just two simple things:
Call java method System.exit(...) at at application's quit point.
For example, if your application is frame based, you can add listener WindowAdapter and and call System.exit(...) inside its method windowClosing(WindowEvent e).
Note: you must call System.exit(...) otherwise your program is error involved.
Avoiding unexpected java exceptions to make sure the exit method can be called always.
If you add System.exit(...) at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called.
This is strongly related to your programming skills.
** Following is a simplest sample (JFrame based) which shows you how to call exit method
import java.awt.event.*;
import javax.swing.*;
public class ExitApp extends JFrame
{
public ExitApp()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args)
{
ExitApp app=new ExitApp();
app.setBounds(133,100,532,400);
app.setVisible(true);
}
}
Not only to close the JFrame but also to trigger WindowListener events, try this:
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).
Initialize your frame like this:
private WindowAdapter windowAdapter = null;
private void initFrame() {
this.windowAdapter = new WindowAdapter() {
// WINDOW_CLOSING event handler
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
// You can still stop closing if you want to
int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
if ( res == 0 ) {
// dispose method issues the WINDOW_CLOSED event
ClosableFrame.this.dispose();
}
}
// WINDOW_CLOSED event handler
#Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
// Close application if you want to with System.exit(0)
// but don't forget to dispose of all resources
// like child frames, threads, ...
// System.exit(0);
}
};
// when you press "X" the WINDOW_CLOSING event is called but that is it
// nothing else happens
this.setDefaultCloseOperation(ClosableFrame.DO_NOTHING_ON_CLOSE);
// don't forget this
this.addWindowListener(this.windowAdapter);
}
You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:
WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
This will close the frame like the "X" button was pressed.
If you really do not want your application to terminate when a JFrame is closed then,
use : setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
instead of : setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Here's a synopsis of what the solution looks like,
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
This examples shows how to realize the confirmed window close operation.
The window has a Window adapter which switches the default close operation to EXIT_ON_CLOSEor DO_NOTHING_ON_CLOSE dependent on your answer in the OptionDialog.
The method closeWindow of the ConfirmedCloseWindow fires a close window event and can be used anywhere i.e. as an action of an menu item
public class WindowConfirmedCloseAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Object options[] = {"Yes", "No"};
int close = JOptionPane.showOptionDialog(e.getComponent(),
"Really want to close this application?\n", "Attention",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
null);
if(close == JOptionPane.YES_OPTION) {
((JFrame)e.getSource()).setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
} else {
((JFrame)e.getSource()).setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE);
}
}
}
public class ConfirmedCloseWindow extends JFrame {
public ConfirmedCloseWindow() {
addWindowListener(new WindowConfirmedCloseAdapter());
}
private void closeWindow() {
processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
Based on the answers already provided here, this is the way I implemented it:
JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame stuffs here ...
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
The JFrame gets the event to close and upon closing, exits.
You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program. When this is done you may handle the resulting event sequence exactly as you would if the user has clicked on the [x] button for an OS suppled decorated JFrame.
public void closeWindow()
{
if(awtWindow_ != null) {
EventQueue.invokeLater(new Runnable() {
public void run() {
awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
}
});
}
}
I have tried this, write your own code for formWindowClosing() event.
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int selectedOption = JOptionPane.showConfirmDialog(null,
"Do you want to exit?",
"FrameToClose",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
setVisible(false);
dispose();
} else {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
This asks user whether he want to exit the Frame or Application.
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Posting what was in the question body as CW answer.
Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a WindowEvent.WINDOW_CLOSING at the application's event queue. Here's a synopsis of what the solution looks like
// closing down the window makes sense as a method, so here are
// the salient parts of what happens with the JFrame extending class ..
public class FooWindow extends JFrame {
public FooWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(5, 5, 400, 300); // yeah yeah, this is an example ;P
setVisible(true);
}
public void pullThePlug() {
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
}
}
// Here's how that would be employed from elsewhere -
// someplace the window gets created ..
FooWindow fooey = new FooWindow();
...
// and someplace else, you can close it thusly
fooey.pullThePlug();
If you do not want your application to terminate when a JFrame is closed,
use:
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
instead of:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
From the 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.
might still be useful:
You can use setVisible(false) on your JFrame if you want to display the same frame again.
Otherwise call dispose() to remove all of the native screen resources.
copied from Peter Lang
https://stackoverflow.com/a/1944474/3782247

Categories