I have a class with only static methods and one of them opens a JOptionPane error message dialogue using a JFrame object as component.
This is the class + method:
public class miscMethods { static JFrame errorWindow = null; public static void ErrorPopup(String message) { errorWindow = new JFrame(); errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); errorWindow.setAlwaysOnTop(true); JOptionPane.showMessageDialog(errorWindow, message, "Error", JOptionPane.ERROR_MESSAGE); errorWindow = null; } }
The ErrorPopup method is used inside a JavaFX controller and other places, called like this:
import static code.miscMethods.ErrorPopup; ... ErrorPopup("This is the error message");
Problem is that the application’s process won’t close when I close the the program from the window’s ✕ after the popup appears, because the JFrame was created and shown.
I know the JFrame is the culprit, so I added the errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
but it doesn’t seem to do anything, since the program isn’t closing.
In this question: JFrame and why stay running The accepted answer talks about non-daemon threads, but the only thread I open is a daemon one, so unless JavaFX open one then it can’t be that I believe.
So, why does the process keep running and how can I solve it?
I’m still new to Java so if I made a mistake and/or my code shows bad practices please do point them out!
Edit: I’m using a JFrame because I need the setAlwaysOnTop, since using
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
opens it not on top of the JavaFX window. If there’s a better way let me know.
Advertisement
Answer
This:
errorWindow = null;
does nothing of use since the object is still displayed. You want this instead:
errorWindow.dispose();
Actually, even better, simply get rid of errorWindow
altogether and pass null
as the first parameter to the JOptionPane.