JavaFX Canvas GraphicsContext draw line

Description

JavaFX Canvas GraphicsContext draw line


// Demonstrate drawing. 

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
   public static void main(String[] args) {
      launch(args);//  w ww .  j  av a  2s  .c om
   }

   public void start(Stage myStage) {
      myStage.setTitle("Draw to a Canvas.");
      FlowPane rootNode = new FlowPane();
      rootNode.setAlignment(Pos.CENTER);
      Scene myScene = new Scene(rootNode, 450, 450);
      myStage.setScene(myScene);
      Canvas myCanvas = new Canvas(400, 400);
      GraphicsContext gc;
      // Get the graphics context for the canvas.
      gc = myCanvas.getGraphicsContext2D();

      // Set the stroke and fill color.
      gc.setStroke(Color.BLUE);
      gc.setFill(Color.RED);

      gc.strokeLine(0, 0, 200, 200);

      // Add the canvas and button to the scene graph.
      rootNode.getChildren().addAll(myCanvas);

      // Show the stage and its scene.
      myStage.show();
   }
}



PreviousNext

Related