gpt4 book ai didi

java - Swing 应用程序卡住

转载 作者:行者123 更新时间:2023-12-01 10:55:52 25 4
gpt4 key购买 nike

我对 AWT/Swing 编程还很陌生,所以我没有看到这个问题。当事件被调用时,窗口甚至在删除组件之前就卡住了,我必须手动关闭它。

那么,这段代码有什么问题呢?

@Override
public void actionPerformed(ActionEvent event)
{
if(((JButton)event.getSource()).getName() == "start")
{
for(Component c : QuizShow.frame.getContentPane().getComponents())
{
if(c.getName() == "wrapper")
{
final JPanel wrapper = (JPanel) c;

SwingUtilities.invokeLater
(
new Runnable()
{
public void run() {
wrapper.removeAll();
QuizPanel qp = new MainQuizPanel();
qp.setup();
wrapper.add(qp);
}
}
);

break;
}
}
}

System.out.println(event.getSource());
}

编辑:这是 qp.setup() void:

public void setup()
{
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < 6; j++)
{
questions[i*6+j] = new JButton();
questions[i*6+j].setText(""+i*10);;
add(questions[i*6+j]);
}
}
}

这是 main(String[] args) 类:

SwingUtilities.invokeLater
(
new Runnable()
{
public void run() {
frame = new QuizShowFrame("Quiz Show");
frame.setSize(800, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setVisible(true);
}
}
);

还有 QuizShowFrame 类:

public class QuizShowFrame extends JFrame
{
private static final long serialVersionUID = 1L;

public QuizPanel introPanel = new Intro();

public JPanel p = new JPanel();

public QuizShowFrame(String name)
{
super(name);

this.setLayout(new BorderLayout());

Container c = this.getContentPane();

p.setBorder(new EmptyBorder(5,5,5,5));
p.setName("wrapper");
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
c.add(p);

p.add(introPanel);

try
{
introPanel.setup();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

最后在 Intro 类中:

public void setup()
{
//...skipped JTextPanes...

JButton gameStart = new JButton("Start the quiz show");
gameStart.setName("start");

try {
gameStart.addActionListener(Listener.class.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

add(gameStart);
}

最佳答案

我明白了:

@Override
public void actionPerformed(final ActionEvent e)
{
if(((JButton)e.getSource()).getName().equals("start"))
{
for(final Component c : QuizShow.frame.getContentPane().getComponents())
{
if(c.getName().equals("wrapper"))
{
((JPanel) c).removeAll();
c.repaint();
QuizPanel qp = new MainQuizPanel();
((JPanel) c).add(qp);
qp.setup();
c.validate();

break;
}
}
}
}

This helped me.看来 .validate() 解决了它。

关于java - Swing 应用程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616584/

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