Recursion causes exit to exit all JFrames (terminates app) - java

I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window.
How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance?
Here is the relevant code:
[...]
JMenuItem newMenuItem = new JMenuItem ("New");
newMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new MainWindow();
}
});
fileMenu.add(newMenuItem);
[....]
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
fileMenu.add(exit);
[...]

First you should try JFrame.DISPOSE_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE because EXIT_ON_CLOSE shuts down the application no matter if there are active threads running or not.
If you still have issues you should consider to introduce an instance counter. To react smarter
See also this discussion

I completely removed the frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE); code.
I changed it to DISPOSE_ON_CLOSE and still the problem was still happening. I ended up creating a windowEvent and adding: frame.dispose(); and the behavior is what I wanted.
Here is the code:
frame.addWindowListener(new WindowListener() {
public void windowClosing(WindowEvent e) {
//Allows for multiple instances and properly closing
//only one of the Frames instead of all of them
frame.dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
});

Related

How to close JFrame while operation is still in progress

In my swings windows application after click the run button some operation is executed. If i am try to close window when operation is still in progress, close operation is not working. After complete the execution of process then only close window operation is working. Otherwise it will not responds the close operations.
I have already tried below mentioned codes. But that one is not stopped working
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
or
System.exit(1);
or
setDefaultCloseOperation(EXIT_ON_CLOSE);
or
setDefaultCloseOperation(3);
or
dispose();
}
});
JButton jb = new JButton("Run");
add(jb);
jb.setBounds(10, 30, 100, 30);
setSize(150,150);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// some operations . For Example here i'm add 1E5 data,s in my collection object. again i will replace data's places of each element.
for(int i=0;i<1E5;i++)
{
ll.add(i);
}
for(int i=0;i<1E5;i++)
{
ll.add(1,i);
}
for(int i=0;i<1E5;i++)
{
ll.add(0,i);
}
System.out.println(ll);
}
});
If I am clicking close button, my window terminate the currently executed process and Close the window.
class MyThread extends Thread {
public void run() {
// some operations . For Example here i'm add 1E5 data,s in my collection object
..
..
}
}
Then in your actionPerformed method on your JButton actionlistener you just start the thread :
public void actionPerformed(ActionEvent e) {
new MyThread().start();
}

How to trap Java windowIconified() and windowIDeconified() before updateUiChanged() event?

My Java Swing application uses updateUiChanged() to resize fonts after its jFrame has been resized by the user. But updateUiChanged() is getting triggered when the jFrame is minimized and then maximized which is causing problem
I tried to trap the minimize and maximize events with the following, but they do not execute at all or they execute after the updateUiChanged() which is too late.
How can I trap the minimize and maximize before the updateUiChanged()
See below for the updateUiChanged implementation.
Thanks
private WindowListener wndMinMax;
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
return;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
return;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
updateUiChanged((int) e.getComponent().getWidth(),
(int) e.getComponent().getHeight());
}
}
});
You can use EventQueue.invokeLater to make sure your updateUiChanged call takes place after the WindowEvent. You can track the occurrence of a WindowEvent in a private instance field, so your delayed ComponentListener code can know if the resize was paired with a WindowEvent:
private boolean iconifyStateChanged;
// ...
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
iconifyStateChanged = true;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
iconifyStateChanged = true;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
// This will run after any pending WindowEvents.
EventQueue.invokeLater(() -> {
if (!iconifyStateChanged)
{
updateUiChanged(e.getComponent().getWidth(),
e.getComponent().getHeight()));
}
iconifyStateChanged = false;
});
}
}
});
(getWidth() and getHeight() already return int values, so a cast to int is not necessary.)

Process doesn't terminate when closing

I'm working on a programm and have a problem with closing it.
I added the following to listeners:
KeyListener kl = new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode()== KeyEvent.VK_ESCAPE) {
shutdown();
}
}
};
WindowListener wl = new WindowAdapter() {
public void windowClosing(WindowEvent e){
shutdown();
}
};
public void shutdown()
{
frame.dispose();
System.exit(0);
//dispose of a buffer
}
I also set:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If I run the the programm in eclipse both listeners close the programm and terminate the process. However if I run it with the runnable .jar only the keylistener works correctly. Closing the window normally does close it, but the process isn't terminated. Why is this and how do I fix this?

JPanel key listener not working [duplicate]

This question already has answers here:
How to use Key Bindings instead of Key Listeners
(4 answers)
KeyListener not working (requestFocus not fixing it)
(3 answers)
Closed 5 years ago.
I am making a large program with multiple classes and am having issues with some code that I wrote. My Mouse listener works just fine and using the same steps, my key listener does not. My code is as follows;
main method
public static void main(String[] args) {
window._init_(panel);
}
Window init method:
public void _init_(JPanel panel){
window = new JFrame("Asteroid");
window.setPreferredSize(size);
window.setDefaultCloseOperation(closeOpp);
window.add(panel);
window.getContentPane();
window.setResizable(resizable);
window.setFocusable(focusable);
window.pack();
window.setLocationRelativeTo(location);
window.setVisible(visibility);
}
Panel init method:
public MainPanel(){
//panel initialization
System.out.println("inside constructor");
panel = new JPanel();
this.add(panel);
this.addKeyListener(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.setSize(Window.size);
this.setFocusable(Window.focusable);
this.add(b);
this.setVisible(Window.visibility);
}
Panel listener methods
#Override
public void keyPressed(KeyEvent e) {
System.out.println("key pressed");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("key released");
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouse clicked");
}
public void keyTyped(KeyEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
ps. The panel implements all of the used listeners, all variables are defined, and the program runs with no errors
Your setting you focus to your frame rather than the JPanel, But even changing the focus to the JPanel will provide a level of unpredictable behavior because it is really easy to lose focus of the JPanel. I suggest you use Key Binding or Change your keylistner method and other override methods to attach to the JFrame rather than the JPanel to assure focus is kept during use of application.

Java - How to "unhide" a JFrame

I am quite new to Java, but familiar with native Android dev so bear with me xD. I created an application that creates a JFrame. Then I set the closeOperation to: setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);.
It performs as expected, the frame is hidden and this is what I want (when I close). I need the application to keep on running (only once instance), because I am running a thread in the background that is performing an operation.
My actionListener on my button in my JFrame currently does this: setVisible(false);
My question is this, how can I maximize the JFrame again after it has been hidden? Would it be possible to display the frame when the user clicks on the minimized application in the task bar? Is there some type of listener that I need to implement?
Thanks in advance, any advice will be appreciated
UPDATE
For this solution to work correctly you need to do the following. Also have a look at XtremeBaumer's answer for this to make sense.
On JFrame creation setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);.
When you want to minimize the app (on click possibly) frame.setState(Frame.ICONIFIED);.
When you want to maximize the app again frame.setState(Frame.NORMAL); in windowDeiconified event.
One last thing, if you want to also minimize your app when the user clicks on the exit button (red x) add this to the windowClosing event frame.setState(Frame.ICONIFIED);.
this.addWindowListener(new WindowListener(){
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
setState(Frame.ICONIFIED)
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
this.setVisible(true);
//this should be what you want
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
}
});
i hope this solves your question. add it to your JFrame

Categories