gpt4 book ai didi

java - Swing 动画开始停止

转载 作者:行者123 更新时间:2023-12-02 04:50:15 25 4
gpt4 key购买 nike

这是我的第一篇文章,所以请原谅我初学者的错误。

我的程序的结构如下:

我有一个类,它基本上创建一个对象数组:

class fieldCreator extends JPanel
{
...
fieldCell[] fieldArray;
...
public fieldCreator()
{
while (counterVar < arraySize)
{
// fill the array randomly with one object out of three different classes
if ((int)(Math.random()) == 0)
this.fieldArray[counterVar] == new cellType0();
...
counterVar++;
}
}
public moveMethod()
{
// rearange the content of the array by a certain algorithm
...
try
{
Thread.sleep(150L); // this is to slow down the loop frequency
}
catch (Exception e) {}
}
public void paintComponent (Graphics g)
{
while (counterVar < arraySize)
{
// draw a rectangle for each object in the array in a specific color
// create the illusion of a 2D field
counterVar++;
}
}
}

主类创建框架并执行方法:

class Main extends JPanel 
{
...
public static fieldCreator myField;
...
public static void main (String[] args)
{

main myMain = new main();
myField = new fieldCreator();

main.framework();

// !!! this loop is what i want to start/stop by a button bash !!!
while(true)
{
myField.moveMethod();
myField.repaint();
}
}
public void frameWork()
{
JFrame myFrame = new JFrame();
JButton startButton = new JButton ("Start");
JButton stopButton = new JButton ("Stop");
startButton.addActionListener(new startListener());
stopButton.addActionListener(new stopListener());
myFrame.getContentPane().add(BorderLayout.NORTH, startButton);
myFrame.getContentPane().add(BorderLayout.CENTER, myField);
myFrame.getContentPane().add(BorderLayout.SOUTH, stopButton);
...
}

class startListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//this does not work!!!
//while(true)
//{
// myField.moveMethod();
// myField.repaint();
//}
}
}

class stopListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// ---- this needs to be implemented ----
}
}
}

通过 IDE 启动和停止程序,该程序可以正常工作,该字段在每个周期都会刷新并正确显示。但当涉及到实现按钮时,它根本不刷新。

我希望代码的缩短不会影响可理解性:)我感谢每一个帮助!

最佳答案

ActionListener 启动动画不起作用的原因是循环阻塞了 event dispatch thread 。从 main() 运行时代码似乎可以工作的原因是 main() 是在另一个线程中运行的。

对于像您一样的简单、定时重复调用,最简单的方法是使用 swing Timer .

顺便说一句,组件也应该是 created在美国东部时间。

关于java - Swing 动画开始停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307399/

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