我正在尝试复制最初扩展 Applet 类的代码。但是下面的代码对于 a 总是正确的Frame
。我知道如果 Frame也为真,那isShowing()
将始终返回真。isVisible()
除非setVisible()
显式设置为 false,isShowing()
否则将返回 true。
我的目标是在应用程序框架最小化时暂停守护线程循环。
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
}
});
}
实施建议(鲍里斯·帕夫洛维奇)
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();
}
}