我的程序结构如下:
我有一个基本创建对象数组的类:
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启动和停止程序,该程序正常工作,该字段在每个周期刷新并正确显示。但是当涉及到实现按钮时,它根本不刷新。
我希望缩短代码不会影响可理解性:) 我感谢你的一切帮助!
答案 0 :(得分:2)
从ActionListener
开始动画的原因不起作用,是循环阻止event dispatch thread。从main()
运行时代码似乎工作的原因是main()
在另一个线程中运行。
对于一个简单的,定时的重复通话,就像你一样,最简单的就是使用摆动Timer。
作为旁注,在EDT中组件也应该是created。
答案 1 :(得分:0)
我解决了以下问题:
class Main extends JPanel
{
public static void main(String[] args)
{
...
timer = new Timer(timerDelay, main.new timerListener());
...
}
class timerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
myField.moveMethod();
myField.repaint();
}
}
class startButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
timer.start();
startButton.setText("RUNNING...");
}
}
class stopButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
timer.stop();
startButton.setText("START");
}
}
}