1
我已经编码了一个简单的模拟,其中2个以不同速度移动的球试图移动到框架的中间,然后移回到它们的起始位置。在最后指定的totalTime
,我结束了模拟并记录了这些数据。Java Swing在一个循环中运行多个模拟
我的问题是,是否有可能循环并自动运行多个模拟?目前,当我的totalTime
启动时,动画只会冻结,但窗口不会关闭。理想情况下,我猜想,我希望看到旧窗口关闭,新窗口以不同球的新速度弹出。
所以我的代码看起来是这样的:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
double rSpeed = 0;
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setSize(500, 500);
Rectangle r = frame.getBounds();
frame.add(new MoveAgents(r.getWidth(), rSpeed));
}
});
}
public MoveAgents(double w, double rFrameSpeed) {
//initialize my 2 balls and their speeds and starting locations
Timer timer = new Timer(15, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
totalTime++;
if (totalTime == 1000) {
timer.stop();
try {
generateCsvFile(OUTPUT_FILE);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//otherwise, do things
}
}
啊谢谢太神奇了!这比我在主要方法中尝试执行循环时遇到的所有问题都要好得多。 – Kevin
@Kevin:我觉得把'javax.swing.Timer'看作提供一个可以外部控制并且不会阻止[EDT]的循环是有帮助的(http://docs.oracle.com/javase/tutorial /uiswing/concurrency/initial.html)。 – trashgod