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