java swing动画开始-停止
这是我的第一篇帖子,所以请原谅我初学者的错误
我的课程结构如下:
我有一个类基本上创建了一个对象数组:
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启动和停止程序,程序运行良好,每个周期字段都会刷新并正确显示。但在实现这些按钮时,它根本不会刷新
我希望代码的缩短不会影响可理解性:) 谢谢你的帮助
# 1 楼答案
从
ActionListener
开始动画不起作用的原因是循环阻止了event dispatch thread。当从main()
运行时,代码似乎可以工作的原因是main()
在另一个线程中运行对于一个简单的定时重复调用,最简单的方法就是使用swing Timer
作为旁注,组件也应该在EDT中created
# 2 楼答案
我解决了这个问题如下: