我构建了一个项目,可以创建类型为Block
的网格6X6元素。当我点击Block
时,会出现一个橙色圆圈。问题是我需要一个按钮,当我点击它时,它会使每个圆圈(即可见)每秒随机向右,向左,向上或向下移动。就像一个圆圈上升,然后它向左移动,然后它再次上升,等等。
class Block extends StackPane {
Rectangle rect = new Rectangle(40, 40);
Circle circ = new Circle(20);
EventHandler a = new EventHandler() {
public void handle(Event t) {
circ.setVisible(true);
}
};
Block() {
rect.setFill(Paint.valueOf("WHITE"));
rect.setStroke(Paint.valueOf("BLACK"));
rect.setOnMouseClicked(a);
circ.setFill(Paint.valueOf("ORANGE"));
circ.setVisible(false);
this.getChildren().addAll(rect, circ);
}
}
public class JavaFXApplication8 extends Application {
@Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
Block[][] matrice = new Block[6][6];
for (int i = 0; i < 6; i++) {
matrice[i] = new Block[6];
for (int j = 0; j < 6; j++) {
matrice[i][j] = new Block();
root.add(matrice[i][j], j, i);
}
}
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
我用javaFX AnimationTimer做了一个示例来说明如何使用它,在这个例子中,AnimationTimer
使得块的随机圆圈可见或不可见(随机)。
在(例如primaryStage.show();
之后将其添加到应用的启动方法中:
// AnimationTimer
new AnimationTimer() {
Random random = new Random();
private long nextSecond = 0;
private long refreshRate = 1_000_000_000L / 6;
@Override
public void handle(long startNanos) {
//refreshing every 1 second/6
//(if you don't set that then it will try to run
// as fast as 50 frames per second)
if (startNanos > nextSecond) {
nextSecond = startNanos + refreshRate;
// Choose some random Numbers
int randomColumn = random.nextInt(6);
int randomRow = random.nextInt(6);
System.out.println(randomColumn + "," + randomRow);
// Do a random item visible
matrice[randomColumn][randomRow].circ.setVisible(random.nextBoolean());
}
}
}.start();
*要移动GridPane
上的块,您可以使用以下方法:
GridPane.setConstraints(Node node,int column,int row);
和其他http://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/GridPane.html