gpt4 book ai didi

java - Swingutilities.invokeLater 和 while 循环

转载 作者:行者123 更新时间:2023-12-02 09:43:34 27 4
gpt4 key购买 nike

我的程序使用一个框架和一个面板,它们在循环中创建一次。框架正常创建并显示,但由于某种原因面板未创建和/或未显示。

任何想法。

干杯。

class GUIThread extends Thread
{
public boolean threadClose;

public GUIThread()
{
SwingUtilities.invokeLater(this);
}
@Override
public void run()
{
JFrame lFrame = null;
JPanel lPanel = null;
boolean lFrameFlag = false;

threadClose = false;

while( !threadClose )
{
if(lFrameFlag == false)
{
lPanel = new JPanel();
lPanel.setSize(580,356);
lPanel.setLocation(10,10);
lPanel.setVisible(true);
lPanel.setBorder( BorderFactory.createLineBorder(Color.BLACK) );

lFrame = new JFrame();
lFrame.setSize(600,400);
lFrame.setLocation(200,200);
lFrame.add(lPanel);
lFrame.setVisible(true);

lFrameFlag = true;
}
}
}
}

public class GUITestHarness
{
public static void main(String[] args)
{
GUIThread lGUIThread = new GUIThread();
}
}

运行时显示框架,但不显示面板。

最佳答案

问题是 while 循环。如果继续执行,则会显示面板,但由于 while 循环是无限循环,因此框架永远不会更新,因为执行被卡在循环中。

因此,如果您尝试不使用无限循环,它应该可以工作。像这样:

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

//here it's better to implement Runnable than extend Thread
//in this case it's the same, but extending thread can lead to strange problems in other cases
public class Frame implements Runnable {

public static void main(String[] args) {
new Frame();
}

public Frame() {
SwingUtilities.invokeLater(this);
}

@Override
public void run() {
JFrame lFrame = null;
JPanel lPanel = null;

lPanel = new JPanel();
lPanel.setSize(580, 356);
lPanel.setLocation(10, 10);
lPanel.setVisible(true);
lPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

lFrame = new JFrame();
lFrame.setSize(600, 400);
lFrame.setLocation(200, 200);
lFrame.add(lPanel);
lFrame.setVisible(true);

}
}

关于java - Swingutilities.invokeLater 和 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56851940/

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