gpt4 book ai didi

java - 为什么我的 Java 程序会创建无限多个窗口? (使用线程和 NO WHILE 循环)

转载 作者:行者123 更新时间:2023-12-01 06:38:17 24 4
gpt4 key购买 nike

问题:因此,我试图了解线程如何处理图形,因此我创建了一个程序,该程序应使用用户线程将屏幕颜色设置为红色。但是,当我运行该程序时,它会无数次地打开我的 JFrame 窗口,并且我必须退出该程序才能停止。我该如何防止这种情况发生?提前致谢。

更新:所以你们很多人都向我解释了罪魁祸首(现在已注释掉):frame.add(new MWT) 重复调用构造函数并创建一个新的对象。但是,如何在没有任何静态实例的情况下简单地将 Canvas 添加到 JFrame 中?谢谢

类代码

    public class MWT  extends Canvas implements Runnable
{
private Thread fast;
public static void main(String [] args){
MWT draw = new MWT();

}
public MWT(){
JFrame frame = new JFrame("Thread Drawings");
frame.setVisible(true);
frame.setFocusable(true);
frame.setSize(600,500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
// CULPRIT
//frame.add(new MWT());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start();
}

private void stop() {
if (fast== null){
return;
}
else{
System.exit(0);
}

}

private void start() {
if (fast != null){
return;
}
else{
fast = new Thread(this);
fast.start();
}

}

@Override
public void run() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
render(g2d);
}
public void render(Graphics2D g2d){
g2d.setColor(Color.RED);
g2d.fillRect(0, 0,600,500);
stop();
}
}

最佳答案

问题出在 add(new MWT()) 行处的 MWT 构造函数。因此,当您构建新的 MWT 时,您将创建一个新的 JFrame,然后再次调用 MWT(),创建一个新的 JFrame ,再次调用MWT(),依此类推。最终你应该会遇到堆栈溢出。

要解决这个问题,您可以扩展 JFrame,并在其构造函数中添加进入其中的组件,或者仅添加当前实例。

public class MWT extends Canvas implements Runnable {
// change the constructor so it doesn't make a new JFrame
// change the constructor so it doesn't add a new instance to the JFrame
// leave the rest unchanged
}

public class ThreadedGraphicsDemo extends JFrame {
private MWT mwt;

public ThreadedGraphicsDemo(MWT mwt) {
this.mwt = mwt;

add(mwt);
// set exit behavior, size, pack, visible etc
}
}

public class Demo {
public static void main(String[] args) {
MWT mwt = new MWT();
ThreadedGraphicsDemo tgd = new tgd(mwt);
}
}

这种方法将允许您在未来轻松更改 GUI 和行为。

快速修复:将 add(new MWT()) 更改为 add(this) 以添加您已实例化的 MWT 实例

关于java - 为什么我的 Java 程序会创建无限多个窗口? (使用线程和 NO WHILE 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27729346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com