Set up Canvas layouts

681 views Asked by At

How I will get white rectangle in the middle of scene. I wanna preserve my own code and the height and width of it. Probably it should be use to set X and Y layouts. but I do not know how. When I set them, it resize it from upper left corner.

Code:

Pane paneCanvas = new Pane();

          final Canvas canvas = new Canvas();
          paneCanvas.setStyle("-fx-background-color: white;");
          canvas.setHeight(32);
          canvas.setWidth(32);

          paneCanvas.getChildren().add(canvas);
          primaryStage.setTitle("Hello World!");
          primaryStage.setScene(scene);
          primaryStage.show();
1

There are 1 answers

0
Mailkov On

Try this example ... for position in middle of scene you can calculate width this formula:

layoutxcanvas=(widthscene/2)-(widthcanvas/2)

layoutycanvas=(heightscene/2)-(heightcanvas/2)

import java.awt.Graphics2D;
import java.awt.Paint;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import javafx.stage.Stage;

public class JavaFXApplication1 extends Application {

    @Override
    public void start(Stage primaryStage) {
       Pane paneCanvas = new Pane();

          final Canvas canvas = new Canvas();
          paneCanvas.setStyle("-fx-background-color: black;");

          canvas.setHeight(32);
          canvas.setWidth(32);
          canvas.getGraphicsContext2D().setFill(Color.WHITE);
          canvas.getGraphicsContext2D().fillRect(0, 0, 32, 32);

          canvas.setLayoutX((300/2)-(32/2));
          canvas.setLayoutY((300/2)-(32/2));

          paneCanvas.getChildren().add(canvas);
          Scene scene=new Scene(paneCanvas,300,300);
          primaryStage.setTitle("Hello World!");
          primaryStage.setScene(scene);
          primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }