Simple example to draw something on JavaFX 2 Canvas:
|
draw on JavaFX 2 Canvas |
package javafx_drawoncanvas;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_DrawOnCanvas extends Application {
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(300, 250);
GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
drawSomething(graphicsContext);
StackPane root = new StackPane();
root.getChildren().add(canvas);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void drawSomething(GraphicsContext gc){
double canvasWidth = gc.getCanvas().getWidth();
double canvasHeight = gc.getCanvas().getHeight();
gc.setFill(Color.RED);
gc.setStroke(Color.BLUE);
gc.setLineWidth(3);
gc.fillRect(
canvasWidth/4, //x of the upper left corner
canvasHeight/4, //y of the upper left corner
canvasWidth/2, //width of the rectangle
canvasHeight/2); //height of the rectangle
gc.strokeOval(
canvasWidth/2, //x of the upper left bound of the oval
canvasHeight/2, //y of the upper left bound of the oval
canvasWidth/2, //width at the center of the oval
canvasHeight/2); //height at the center of the oval
}
}
No comments:
Post a Comment