I’m trying to replicate my code originally made extending the Applet class.
but the code below is always true for a Frame. I understand that isShowing() will always return true if the Frame isVisible() is also true. Unless the setVisible() is explicitly set to false, isShowing() will return true.
My goal is to pause a daemon thread from looping when the application Frame is minimized.
public class Screen extends Applet{
@Override
public void init() {
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
//do stuff
}
@Override
public void componentHidden(ComponentEvent e) {
//Stop doing stuff
}
});
}
Implement suggestion (Boris Pavlović)
public class Screen extends Frame implements Runnable{
private boolean runL;
private Thread thread;
public Screen() {
setSize(256,256);
setVisible(true);
addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
runL = true;
starThread();
}
@Override
public void windowLostFocus(WindowEvent e) {
runL = false;
}
});
}
@Override
public void run() {
while(runL){System.out.println("showing");}
}
private void starThread(){
if(thread == null){
thread = new Thread(this);
thread.start();
} else if(!thread.isAlive()){
thread = new Thread(this);
thread.start();
}
}
Check out the tutorial on “How to Use Focus Subsystem“.
WindowsAdapterallows for overriding different state transitions which may be used to start/stop the computation.