Close JFrame from a JButton process remain alive - java

I have a class developed with windowbuilderpro that i want to close also from a JButton further than with the standard X button on the window, so here the example of the class :
public class MainWindow {
public JFrame frame;
public MainWindow() {
initialize();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void show() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Show the main Frame
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
When i close the window from the X button the window close correctly and the process terminate.
When i close instead from a JButton that have this listener :
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Close the application main form
frame.setVisible(false);
frame.dispose();
}
});
the frame window close correctly but the process remain alive ... Why ?
As you can see there is an AWT-Shutdown thread that start and terminate continuously, How can i achieve the same behaviour of the X button that close also the application process ?
Notes :
System.exit(0); is not suitable because it terminate the application also if there are another background running thread and i don't want that . The MainWindow class should close and release it's resource, the same behaviour that have closing the application with the X button that close the MainWindow instance but if there are background thread running it doesn't kill they but wait until they finished their work...
Enviroment :
JDK 7
Eclipse 3.7.1

not sure what you really needed, that looks like that you create new JFrame again an again, don't do that, create JFrame once and re-use this Container
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // do nothing
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // same as setVisible(false)
then for visibily you can only to call frame.setVisible(true);
for more Confortable is override WindowListener, then you can control some Events

All threads in this code stop when either the x button or the Exit button are activated. Are you getting different behavior?
import java.awt.event.*;
import javax.swing.*;
public class MainWindow {
public JFrame frame;
JButton mntmExit = new JButton("Exit");
public MainWindow() {
frame = new JFrame("Close Me!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Close the application main form
frame.setVisible(false);
frame.dispose();
}
});
frame.add(mntmExit);
frame.pack();
show();
}
public void show() {
//Show the main Frame
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainWindow mw = new MainWindow();
mw.show();
}
});
}
}

Just add one line:
System.exit(0);

Related

How can I get this to run without freezing the GUI

This is a very simplified version of my code to get a better understanding of what I'm doing wrong here. The GUI freezes if the button is pressed. I need to be able to run a while loop if the button is pressed without freezing.
class obj1 extends Thread{
public void run(){
while(true) {
System.out.println("this thread should run when the button is pressed and I should be able to press another button");
}
}
}
class GUI extends Thread{
JFrame frame = new JFrame();
JButton button = new JButton("test1");
JButton button2 = new JButton("test2");
JPanel panel = new JPanel();
String command;
public void run() {
frame.setVisible(true);
panel.add(button);
panel.add(button2);
frame.add(panel);
frame.pack();
buttonOnAction();
}
public void buttonOnAction(){
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
obj1 one = new obj1();
one.start();
one.run();
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
obj1 one2 = new obj1();
one2.start();
one2.run();
}
});
}
}
public class Main{
public static void main(String args[]){
GUI gui = new GUI();
gui.start();
gui.run();
}
}
Why does the GUI freeze?
Don't call run() directly on your Thread object. This immediately executes the run() method and doesn't spawn a new thread. Instead, just call start() as you have and let the system create the thread and call run() when it decides to.
It is also worth pointing out that the proper way to schedule graphical work in Swing is to make sure it ends up on the event dispatch thread. To do this properly, use SwingUtilities#invokeLater(Runnable), which will not wait for the work to complete, or SwingUtilities#invokeAndWait(Runnable), which will.

How do you get AWT graphics to appear on Window open?

I want to be able to have a window listener that when the window is opened, some graphics appear. This comes with some problem though, because you can't set a window listener while the window is set to visible (or at least that's what I've found), but if you wait to set the window to visible until after you set the listener you can't set the Graphics.
This is the code with the window set to visible at the start:
public class FrameTest {
static Frame myFrame;
static Graphics myGraphics;
public static void main(String[] args) {
//Initializing Window
myFrame = new Frame();
myFrame.setTitle("Frame Test");
myFrame.setSize(570, 570);
myFrame.setVisible(true);
myGraphics = myFrame.getGraphics();
myFrame.requestFocus();
//Close Button
myFrame.addWindowListener(new WindowAdapter()
{
public void windowOpened(WindowEvent e)
{
System.out.println("opened");
myGraphics.setColor(Color.red);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

How to tell if a JFrame window has already been opened?

I have a JFrame with a Button that opens a different JFrame. But I want the button to only open the second frame once. Problem is, every time I click it I get a new instance of the frame. This must be a very common problem, since I'm following a book on how to create this GUI. I find it odd that the author didn't mention this "feature".
So how do I keep my button from opening multiple copies of the new frame?
Instead of letting the button create a new JFrame every time, make the second JFrame a member of the first JFrame, and only let the button call jframe2.setVisible(true);:
class JFrame1 {
JFrame2 jframe2=...;
JButton button=...;
JFrame1() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe2.setVisible(true);
}
});
...
}
}
UPDATED!
try this:
JFrame frame2 = new JFrame(); // instance variable
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!frame2.isVisible())
frame2.setVisible(true);
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
frame2.setVisible(false);
frame2.dispose();
}
});
instead of using the JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hope this helps.
You should keep a reference to the sub frame you open for first time. At second time you first check if you have a reference or not and then decide to create a new frame or to put the focus onto the existing open frame.
Example as answer to comment of OP (similar to other answer of #AlexanderTorstling, but not immediately creating the sub frame):
class MainFrame extends JFrame {
private JFrame subFrame = null;
MainFrame() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (subFrame == null) {
subFrame = new JFrame();
...
}
subFrame.setVisible(true);
}
});
}
}
This example has also the advantage to give you the possibility to close the subframe via a registered WindowAdapter if the main frame is closed.
please try this one
JFrame frame2 = new JFrame(); // instance variable
boolean secondWindowIsOpne = false;
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(secondWindowIsOpne == false){
frame2.setVisible(true);
secondWindowIsOpne = true;
}
else{
System.out.println("This Window is already running");
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
secondWindowIsOpne = false;
frame2.setVisible(false);
frame2.dispose();
}
});

Call a method when application closes

In my Swing chat application I have a logout button which is used to logout the user and it works fine. Now I need to logout the user when I close the Swing application window.
I did this in web application when closing browser using JavaScript, but now I need to do this in Swing application.
How can I achieve this?
Call JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
Add a WindowListener to the frame.
Override the appropriate method of the listener to call your closing method, then set the frame invisible and dispose of it.
E.G.
import java.awt.*;
import java.awt.event.*;
import java.net.URI;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class CheckExit {
public static void doSomething() {
try {
// do something irritating..
URI uri = new URI(
"http://stackoverflow.com/users/418556/andrew-thompson");
Desktop.getDesktop().browse(uri);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setPreferredSize(new Dimension(400, 100));
gui.setBackground(Color.WHITE);
final JFrame f = new JFrame("Demo");
f.setLocationByPlatform(true);
f.add(gui);
// Tell the frame to 'do nothing'.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
WindowListener listener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent we) {
int result = JOptionPane.showConfirmDialog(
f, "Close the application");
if (result==JOptionPane.OK_OPTION) {
doSomething();
f.setVisible(false);
f.dispose();
}
}
};
f.addWindowListener(listener);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Use the window events on your JFrame, there you have the Methods you might need (windowclosed();) for example. it´s the WindowListener
edit :
you can say
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
but your Windowlistener still works if you push the X (close button)
there you override the method windowClosing, with this code
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(TestFrame.this, "do you really want to close?","test",JOptionPane.YES_NO_OPTION);
if(i == 0) {
System.exit(0);
}
}
this will do the work

Need advice on creating a closing button for a small Java program

I am a novice as already stated and looking to create a button to close the program out. I am not talking about making sure the typical window close (Red X) terminates the program. I wish to make an additional button within my frame that when clicked will terminate the program as well.
You can add an ActionListener to your button which, upon action being performed, exits from the JVM.
yourButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
If you have set up the main application frame's (JFrame) defaultCloseOperation to JFrame.EXIT_ON_CLOSE then simply calling the frame's dispose method will terminate the program.
JButton closeButton = JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourReferenceToTheMainFrame.dispose();
}
});
If not, then you will need to add to the actionPerformed method a call to System.exit(0);
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GoodbyeWorld {
GoodbyeWorld() {
final JFrame f = new JFrame("Close Me!");
// If there are no non-daemon threads running,
// disposing of this frame will end the JRE.
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// If there ARE non-daemon threads running,
// they should be shut down gracefully. :)
JButton b = new JButton("Close!");
JPanel p = new JPanel(new GridLayout());
p.setBorder(new EmptyBorder(10,40,10,40));
p.add(b);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener closeListener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
f.setVisible(false);
f.dispose();
}
};
b.addActionListener(closeListener);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new GoodbyeWorld();
}
};
SwingUtilities.invokeLater(r);
}
}
If you are extending the org.jdesktop.application.Application class (Netbeans would do that) you could invoke exit() in your app class, so:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourApp.exit();
}
});

Categories