gpt4 book ai didi

java - 可视化循环内 JPanel 的变化

转载 作者:行者123 更新时间:2023-12-01 18:03:02 25 4
gpt4 key购买 nike

我是 Java swing 编程新手。我想做一个依次显示红色和蓝色的框架。因此,我采用了 2 个子 JPanel,1 个用于红色,另一个用于蓝色,以及一个 for 循环。在每次迭代中,我从父面板中删除一个面板并添加另一个面板。但是,当我运行该程序时,它只显示框架的最后状态。

谁能解释一下为什么吗?使程序像这样工作的预期方法是什么?我的代码:

public class Test2 extends JFrame {

public Test2() {

JPanel Red = new JPanel(new BorderLayout());
JPanel Blue = new JPanel(new BorderLayout());

//...initialize Red and Blue
Red.setBackground(Color.red);
Blue.setBackground(Color.blue);
Red.setPreferredSize(new Dimension(200,200));
Blue.setPreferredSize(new Dimension(200,200));


JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200,200));

add(panel);

pack();

setTitle("Border Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

int M = 1000000; //note that, I made a long iteration to not finish the program fast and visualize the effect
for(int i=0;i<M;i++)
{
if(i%(M/10)==0) System.out.println(i); //to detect whether the program is running

if(i%2==0)
{
panel.removeAll();
panel.repaint();
panel.revalidate();
panel.add(Red,BorderLayout.CENTER);
}
else
{
panel.removeAll();
panel.repaint();
panel.revalidate();
panel.add(Blue,BorderLayout.CENTER);
}
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Test2 ex = new Test2();
ex.setVisible(true);
}
});
}}

最佳答案

不要使用循环。只有在整个循环执行完毕后,Swing 才会重新绘制框架。

相反,您需要使用 Swing Timer。当计时器触发时,您将调用您的逻辑。阅读 Swing 教程中关于 How to Use Swing Timers 的部分.

下面是一个简单的计时器示例,它仅显示每秒的时间:Update a Label with a Swing Timer

此外,请勿删除/添加面板。相反,您可以使用卡片布局并 Swing 可见面板。再次阅读 How to Use CardLayout 上的教程.

关于java - 可视化循环内 JPanel 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193514/

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