W
W
WannaCreative2016-08-17 00:21:22
Java
WannaCreative, 2016-08-17 00:21:22

Java FX how to center an element?

There is a code

package sample;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.stage.Stage;

public class Main extends Application
{
    public static void main(String[] args)
    {
        Application.launch(args);
    }

    @Override
    public void start(Stage window)
    {
        Group root = new Group();
        Scene scene = new Scene(root, 800,800);

        ProgressBar prbar = new ProgressBar();
        prbar.setMinSize(250,50);
        root.getChildren().add(prbar);


        window.setScene(scene);
        window.setResizable(false);
        window.setTitle("Title");
        window.show();
    }
}

How to center the progress bar?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rzoner, 2016-09-28
@WannaCreative

The StackPane places everything in the center by default.

S
Stanislav Zemlyakov, 2016-08-17
@redtom

I would just change the Group to any other container that has a .setAlignment() method

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application
{
    public static void main(String[] args)
    {
        Application.launch(args);
    }

    @Override
    public void start(Stage window)
    {
        VBox root = new VBox(); //◄
        Scene scene = new Scene(root, 800,800);

        ProgressBar prbar = new ProgressBar();
        prbar.setMinSize(250,50);

        root.setAlignment(Pos.CENTER); //◄
        root.getChildren().add(prbar);

        window.setScene(scene);
        window.setResizable(false);
        window.setTitle("Title");
        window.show();
    }
}

WannaCreative: Any element (such as a button, checklist, etc.) that you place on the stage must end up in some kind of container. Containers have a list of properties and methods they support. In this case, setAlignment is to set the orientation for child elements.
My advice: always use containers, they are more convenient to work with.
So the button in our case should lie somewhere.
In general, it's better to work with *.fxml from SceneBuilder. Setting scenes manually is a dubious task, in my opinion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question