異なる速度で移動する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