I seem to have found a really STRANGE (error?) in java while using swing JFrames.
Basically my program is like this, I have a JFrame that comes up when I run my program. That one seems to be working perfectly normal.
I have a button that when you click it, runs
this.setVisible(false)
and creates a new (different) JFrame.
Where the hang happens, is in the constructor/initalize method of this new JFrame, specifically when doing setVisible(true);
I tried putting the setVisible(true) before, after, and even at random places inside the initialize.
It seems like the setVisible only works about 70% of the time. The rest of the time the entire java vm seems to freeze, meaning the only way I can quit my program is by using the terminate button in the IDE,
or if running as a JAR (the compiled version of my code), then ending the process using task manager or some equilivalent.
I am about 99% sure this is NOT a problem with my code, however a problem with Java.
However, I do not understand exactly WHY it is working sometimes and other times not.
I managed to come up with a solution (work-around) however it uses the deprecated method
Thread.stop();
and is not at all ideal (although to the user it is pretty much the same).
for the workaround I will run the following commands in place of
setVisible(true);
and
setVisible(false);
respectively [called from within the class implementing JFrame, so "this" = ClassName.this (implements JFrame):
{code}new SetVisibleThread(this, true);
new SetVisibleThread(this, false);
The code for SetVisibleThread is as follows:
public class SetVisibleThread implements Runnable {
private JFrame makeVisible;
private boolean desired;
private boolean worked=false;
@SuppressWarnings("deprecation")
public SetVisibleThread(JFrame makeVisible, boolean desired) {
this.makeVisible=makeVisible;
this.desired=desired;
while (!worked) {
Thread t=new Thread(this,"make_visible");
System.out.println("Attemptting to set visibility: " + desired);
t.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.stop();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
if (makeVisible.isVisible()) {
// insurance... ?
makeVisible.setVisible(!desired);
worked=false;
}
makeVisible.setVisible(desired);
if (desired) {
makeVisible.toFront();
}
worked=true;
}
}
The reason for the first if in the run method is that sometimes I would find the window would actually not be visible on the screen, but isVisible() would be returning true...
this was the only way to insure 100% that the window would be made visible.
if anyone has ideas about why this error might be happening that would be cool to read.
personally, its not a big deal because my workaround works O.K. but I would rather not be using the deprecated methods, and I would rather java worked the way it was intended.
Thanks,
Robert Noack