Search code examples
javacanvasjavafxlayoutborderpane

javafx borderpane with only 2 nodes


i am currently working on a Programm that requires a canvas and a label to at the Side. I've tried using Borderpane to accomplish this, but failed. One of my Problems is, that BorderPane requires either no, one or five objects to initialise. I only need two. My other Problem is, that ohly the canvas(center) shows, even if i initialise BorderPane with 5 Objects. This is my Code:

    primaryStage.setTitle("Drawing Operations Test");
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent event) {
            try {
                scheduler.shutdown();
                stop();
            } catch (Exception ex) {
                System.err.println("stop failed: " + ex);
                ex.printStackTrace();
            }
        }
    });

   // Group root = new Group();
    Canvas canvas = new Canvas(size, size);
    gc = canvas.getGraphicsContext2D();
    label.setTextFill(Color.web("#000000"));
    label.setFont(new Font("Arial", 30));
    label.setContentDisplay(ContentDisplay.RIGHT);


    //BorderPane.setCenter(canvas);
    //BorderPane.setRight(label);
    //BorderPane.setAlignment(canvas, Pos.CENTER);
    //BorderPane.setAlignment(label, Pos.BASELINE_RIGHT);



    BoxBlur blur = new BoxBlur();
    blur.setWidth(1);
    blur.setHeight(1);
    blur.setIterations(1);
    gc.setEffect(blur);

    drawShapes(gc, size);


            BorderPane.setAlignment(canvas,Pos.TOP_CENTER);
    // Set the alignment of the Bottom Text to Center

    // Set the alignment of the Right Text to Center
    BorderPane.setAlignment(label,Pos.CENTER_RIGHT);

            BorderPane root = new BorderPane(canvas,label);

    // Set the Size of the VBox
    root.setPrefSize(400, 400);     
    // Set the Style-properties of the BorderPane
    root.setStyle("-fx-padding: 10;" +
            "-fx-border-style: solid inside;" +
            "-fx-border-width: 2;" +
            "-fx-border-insets: 5;" +
            "-fx-border-radius: 5;" +
            "-fx-border-color: blue;");

    // Create the Scene
    Scene scene = new Scene(root);
    // Add the scene to the Stage
    primaryStage.setScene(scene);
    // Set the title of the Stage
    primaryStage.setTitle("A simple BorderPane Example");
    // Display the Stage
    primaryStage.show();

How can i fix this Problem ?


Solution

  • You can achieve what you are asking for simply with

    BorderPane root = new BorderPane();
    root.setCenter(canvas);
    root.setRight(label);
    

    or

    BorderPane root = new BorderPane(canvas);
    root.setRight(label);
    

    or

    BorderPane root = new BorderPane(canvas, null, label, null, null);
    

    The documentation has an example of creating a border pane with three nodes, and explicitly states "Any of the positions may be null."