import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author kcr */ public class CanvasTest extends Application { private static final int WIDTH = 600; private static final int HEIGHT = 450; private static final int SIZE = 10; private static final int INC = 20; private static final int X_MIN = 10; private static final int Y_MIN = 10; private static final int X_MAX = WIDTH - SIZE; private static final int Y_MAX = HEIGHT - SIZE; Canvas canvas; double x = X_MIN; double y = Y_MIN; @Override public void start(Stage stage) { stage.setTitle("CanvasTest"); Group root = new Group(); Scene scene = new Scene(root, WIDTH, HEIGHT); canvas = new Canvas(WIDTH, HEIGHT); root.getChildren().add(canvas); stage.setScene(scene); stage.show(); final GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.DARKBLUE); gc.fillRect(0, 0, WIDTH, HEIGHT); KeyFrame keyFrame = new KeyFrame(Duration.millis(100), new EventHandler() { @Override public void handle(ActionEvent t) { gc.setFill(Color.RED); gc.fillRect(x, y, SIZE, SIZE); x += INC; if (x >= X_MAX) { x = X_MIN; y += INC; if (y >= Y_MAX) { gc.setFill(Color.DARKBLUE); gc.fillRect(0, 0, WIDTH, HEIGHT); y = Y_MIN; } } } }); Timeline t = new Timeline(keyFrame); t.setCycleCount(Timeline.INDEFINITE); t.play(); } /** * @param args the command line arguments */ public static void main(String[] args) { Application.launch(args); } }