How do I center JavaFX controls

前端 未结 2 1425
轻奢々
轻奢々 2021-02-05 21:15

More specifically, why are my JavaFX controls not being centered? Here are two screenshots, the first just after starting (I moved the window into a more visible spot but have n

2条回答
  •  深忆病人
    2021-02-05 22:06

    Resize Issue

    Make sure you are adding a size to your JFrame

    frame.setSize(500, 300);
    

    Center Issue

    I am not sure whether you are taking about centering your frame or the JavaFX controls in the GridPane, so I am adding answers for both of them

    Frame Screen Centering

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dim.width/2-frame.getSize().width/2, 
                                            dim.height/2-frame.getSize().height/2);
    

    screenshot

    GridPane Child Centering

    You need to add

    GridPane.setHalignment(child, HPos.CENTER);
    

    to your code, remove the rest unnecessary code

    I edited your code :

    {
        Label statusLabel = new Label("Checking for Updates...");
        //statusLabel.setAlignment(Pos.CENTER);
        //statusLabel.setTextAlignment(TextAlignment.CENTER);
        rootGrid.add(statusLabel, 0, 0);
        GridPane.setHalignment(statusLabel, HPos.CENTER);
    }
    {
        ProgressBar progressBar = new ProgressBar();
        progressBar.setProgress(-1);
        progressBar.setPrefWidth(400); // 1/5 the width of the screen
        rootGrid.add(progressBar, 0, 1);
    }
    {
        Button downloadButton = new Button("Get it!");
        //downloadButton.setAlignment(Pos.CENTER);
        rootGrid.add(downloadButton, 0, 2);
        GridPane.setHalignment(downloadButton, HPos.CENTER);
    }
    

    and the result is

    enter image description here

提交回复
热议问题