0
votes

I wondered how its possible to center certain elements within a scene.

The method which I understood the scene works, you for example:

  1. want a search - TextField

  2. add TextField to HBox/VBox

  3. add HBox to scene

  4. Scene show.

Now within a HBox/VBox positioning of elements is quite simple (vbox.setAlignment(Pos.BOTTOM_CENTER)), however I wondered if there is a possibility to do such things within a Scene or how is the positioning working in JavaFX?

1
A Scene has a root of type Parent. Everything in the Scene is a descendant of that Parent. You need to use the proper layout, or combination thereof, to create the desired UI. It's these layouts that position and size their children. Typically you would use the subclasses of Pane or use a Group, both of which inherit from Parent. See Working with Layouts in JavaFX and the javafx.scene.layout package for more information.Slaw

1 Answers

0
votes

You can change the positioning of the elements in a HBox or VBox with in a scene.

Example hbox.fxml :

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>

<HBox fx:id="hBox" prefHeight="213.0" prefWidth="473.0" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1" fx:controller="HboxController">
<TextField fx:id="textfield1" alignment="CENTER"/>
</HBox>

Example HboxController.java

    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.geometry.Pos;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.HBox;

    import java.net.URL;
    import java.util.ResourceBundle;

    public class HboxController implements Initializable {

    @FXML
    private HBox hBox;

    @FXML
    private TextField textfield1;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        hBox.setAlignment(Pos.CENTER);
    }
}

This will center the elements in the HBox.

hbox.setAlignment(Pos.Center);

Also these links might be of help to you too JavaFX center Button in VBox, SetAlignment method in JavaFX

If you are trying to get a particular node that is an element of the hbox, you can either give it an id and refer to it that way or this link might be helpful otherwise How do I get all nodes in a parent in JavaFX?