0

I spent a long time searching for how to add a position to an AnchorPane (not declared means like that: setMethode(new AnchorPane());). Adding Layout (x,y), Setting Pref(Width and Height) etc.

I tried that but it didn't work:

           .someMethode(new AnchorPane(
                   .setLayoutX(12);
                   .setLayoutY(222);
                   .setPrefWidth(1026);
           ));

Can anybody help me?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
A_A
  • 11
  • 6

1 Answers1

1

What you're probably refering to is the double brace initialization (see What is Double Brace initialization in Java?). You'd need to write it like this:

.someMethode(new AnchorPane() {{
               setLayoutX(12);
               setLayoutY(222);
               setPrefWidth(1026);
       }});

However I consider this a bad practice, since you create a new anonymus class by using the double brace initialisation.

Alternatives:

  • Use a variable

    AnchorPane pane = new AnchorPane();
    pane.setLayoutX(12);
    pane.setLayoutY(222);
    pane.setPrefWidth(1026);
    ...
    <some expression>.someMethode(pane);
    
  • create a method doing this:

    static AnchorPane createAnchorPane(double layoutX, double layoutY, double prefWidth) {
        AnchorPane pane = new AnchorPane();
        pane.setLayoutX(layoutX);
        pane.setLayoutY(layoutY);
        pane.setPrefWidth(prefWidth);
        return pane;
    }
    ....
    <some expression>.someMethode(createAnchorPane(12, 22, 1026));
    
  • Create a builder for AnchorPanes
  • Use fxml and FXMLLoader, which allows you to create a node structure from a file. It may be easier to create a bigger node structure that way. This would be a fxml file for your AnchorPane
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane prefWidth="1026" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" layoutX="12" layoutY="222" >
    <!-- add something else here??? -->
</AnchorPane>
Community
  • 1
  • 1
fabian
  • 80,457
  • 12
  • 86
  • 114