我向用户显示一个网格窗格,并在for循环中将其更新了两次。我需要做的是,在每次更新之前,我需要创建一秒钟的延迟,以便让用户看到该状态的一秒钟。
VisualizationThread visualizationThread = new VisualizationThread(matrix, bestIndividual, centerX, centerY);
for(int i=0; i<bestIndividual.size(); i++){
switch (bestIndividual.get(i)){
case 1:
visualizationThread.setCurrentX(visualizationThread.getCurrentX()-1);
break;
case 2:
visualizationThread.setCurrentY(visualizationThread.getCurrentY()+1);
break;
case 3:
visualizationThread.setCurrentX(visualizationThread.getCurrentX()+1);
break;
case 4:
visualizationThread.setCurrentY(visualizationThread.getCurrentY()-1);
break;
}
visualizationThread.run();
try {
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
VisualizationThread类:
public class VisualizationThread implements Runnable{
private ArrayList<ArrayList<Integer>> matrix;
private ArrayList<Integer> solution;
private int currentX;
private int currentY;
private Stage primaryStage;
public VisualizationThread(ArrayList<ArrayList<Integer>> matrix, ArrayList<Integer> solution, int currentX, int currentY){
this.matrix = matrix;
this.solution = solution;
this.currentX = currentX;
this.currentY = currentY;
this.primaryStage = new Stage();
}
public void run() {
if(primaryStage.isShowing()){
primaryStage.close();
}
BorderPane root = new BorderPane();
GridPane grid = new GridPane();
grid.setPadding(new Insets(10));
grid.setHgap(10);
grid.setVgap(10);
StackPane[][] screen_buttons = new StackPane[matrix.size()][matrix.size()];
for (int y=0;y<matrix.size();y++) {
for (int x=0;x<matrix.get(y).size();x++) {
screen_buttons[y][x] = new StackPane();
Rectangle rec = new Rectangle(30,30);
if(x == currentX && y == currentY){
rec.setFill(Color.GREEN);
}else {
rec.setFill(matrix.get(x).get(y) == 0 ? Color.YELLOW : Color.RED);
}
rec.setStyle("-fx-arc-height: 10; -fx-arc-width: 10;");
screen_buttons[y][x].getChildren().addAll(rec);
grid.add(screen_buttons[y][x], x, y);
}
}
//container for controls
GridPane controls = new GridPane();
root.setCenter(grid);
root.setBottom(controls);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public int getCurrentX() {
return currentX;
}
public void setCurrentX(int currentX) {
this.currentX = currentX;
}
public int getCurrentY() {
return currentY;
}
public void setCurrentY(int currentY) {
this.currentY = currentY;
}
}
我的问题是,在所有迭代完成之前,该阶段看起来是空的。但是我想显示每个迭代一段时间,我尝试使用Thread.sleep()来实现。显然它没有用。这是为什么?我该如何实现?最好的问候,