Closing the window in Button press.
I would like to close the window in which the Button is defined.
So,if the user presses the JButton (Exit),the window should close down.
For this I am using the flwg code,but the window doesnt exit.
JButton button =new JButton("Stop Engine");
button.addActionListener(this);
publicvoid actionPerformed(ActionEvent e){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Am I missing out anything?
No luck.
public void actionPerformed(ActionEvent e) {
System.out.println("Engine Stopping");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dispose();
}
Still the window is open till i click on the 'x'
please can someone help.
I am trying to close the window in which the 'Stop Engine' button is defined.
For this I am using:
button.addActionListener(this);
public void actionPerformed(ActionEvent e) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//dispose();
}
But the window still doesnt close,till I click on the 'X' icon.
Am I missing anytihng?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
These methods only set a flag that is used later (by JVM) to determine the way the container is going to be closed, when the user press the 'X' icon which is the default close operation.
They do not perform any what so over action regarding the closing operation, besides their named setDefaultCloseOperation , which means they assign a value to some variable, or field.
Having the above methods in an actionListener isn't wise, note that the second call overrides the flag set by the first call.
You could use System.exit() inside the actionPerformed but this is not recommended.
You could also use dispose(), just make sure you are calling the dispose method of the container(such as JFrame) .