我如何将 JavaFX 控件居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26169445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:57:08  来源:igfitidea点击:

How do I center JavaFX controls

javauser-interfacejavafxui-design

提问by Supuhstar

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 not yet resized it), and the second is just after resizing it to show off my problem. Bonus points if you help me ensure it's properly sized (on all DPIs) when it first shows:

更具体地说,为什么我的 JavaFX 控件没有居中?这是两个屏幕截图,第一个刚开始后(我将窗口移到更明显的位置但尚未调整其大小),第二个是在调整其大小以显示我的问题之后。如果您帮助我确保它第一次显示时大小合适(在所有 DPI 上),则加分:

A small window with the title "Checking", and only a small sliver of content, on top of its own codeThe same scene, but the window now shows the title "Checking for Updates...", its content more apparent, where the components are centered, but not their content.

一个标题为“正在检查”的小窗口,只有一小部分内容,位于其自己的代码之上相同的场景,但窗口现在显示标题“检查更新...”,其内容更明显,组件居中,但不是它们的内容。

Conveniently, the relevant code is included in those screenshots. If you still need it as text, here you go:

方便的是,相关代码包含在这些屏幕截图中。如果您仍然需要将其作为文本,请执行以下操作:

private void initJFXPanel(JFXPanel holder)
{
    {
        {
            rootGrid = new GridPane();
            rootGrid.setAlignment(Pos.CENTER);
            rootGrid.setPadding(new Insets(16));
            rootGrid.setHgap(16);
            rootGrid.setVgap(8);
        }

        interior = holder.getScene();
        if (interior == null)
            holder.setScene(interior = new Scene(rootGrid));
        interior.setRoot(rootGrid);

    }
    {
        statusLabel = new Label("Checking for Updates...");
        statusLabel.setAlignment(Pos.CENTER);
        statusLabel.setTextAlignment(TextAlignment.CENTER);
        rootGrid.add(statusLabel, 0, 0);
    }
    {
        progressBar = new ProgressBar();
        progressBar.setProgress(-1);
        progressBar.setPrefWidth(Constants.MAX_WIN_BOUNDS.width / 5d); // 1/5 the width of the screen
        rootGrid.add(progressBar, 0, 1);
    }
    {
        downloadButton = new Button("Get it!");
        downloadButton.setAlignment(Pos.CENTER);
        rootGrid.add(downloadButton, 0, 2);
    }
    holder.setMinimumSize(new Dimension((int)(rootGrid.getPrefWidth() + .5), (int)(rootGrid.getPrefHeight() + .5)));
    setMinimumSize(holder.getMinimumSize());
}

采纳答案by jewelsea

Solution

解决方案

Place your controls in a VBox (or other similar root layout pane) and set the VBox alignmentto center.

将控件放在 VBox(或其他类似的根布局窗格)中,并将 VBox 对齐设置为居中。

Layout Advice

布局建议

This is my personal advice on starting with layout in JavaFX (it's just advice and not applicable to everybody, you can take it or leave it):

这是我在 JavaFX 中从布局开始的个人建议(这只是建议,并不适用于所有人,您可以接受或放弃):

  • Your window and all controls and layouts will automatically size to their preferred size.
  • Let the in-built layout managers and layout system do as many calculations for you as possible with you just providing the minimum layout hints necessary to get your result.
  • Stick to using JavaFX only or Swing only code until you are familar with both styles of code development and really need to mix them.
  • Use the SceneBuilder tool to play around with different layouts and get familiar with JavaFX layout mechanisms.
  • Study the JavaFX layout tutorial.
  • Review a presentation on JavaFX layout.
  • To center a stage the screen call stage.centerOnScreen().
  • Consider using the built-in dialog support of Java 8u40 (when it is released).
  • 您的窗口和所有控件和布局将自动调整为它们的首选大小。
  • 让内置的布局管理器和布局系统为您做尽可能多的计算,您只需提供获得结果所需的最少布局提示。
  • 坚持只使用 JavaFX 或只使用 Swing 代码,直到您熟悉这两种代码开发风格并且确实需要混合使用它们。
  • 使用 SceneBuilder 工具尝试不同的布局并熟悉 JavaFX 布局机制。
  • 学习JavaFX 布局教程
  • 查看有关 JavaFX 布局演示文稿
  • 要使舞台居中,请调用stage.centerOnScreen()屏幕。
  • 考虑使用 Java 8u40(发布时)的内置对话框支持。

Hi-dpi support

高dpi支持

See the answer to:

请参阅以下答案:

FXML based sample code for your dialog

对话框的基于 FXML 的示例代码

update-check

更新检查

You can load the following up in SceneBuilderto easily display it:

您可以在SceneBuilder 中加载以下内容以轻松显示它:

<?xml version="1.0" encoding="UTF-8"?>

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

<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="8.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label fx:id="updateStatus" text="Checking for Updates..." />
      <ProgressBar fx:id="updateProgress" prefWidth="200.0" progress="0.0" />
      <Button fx:id="updateAction" mnemonicParsing="false" text="Get it!" />
   </children>
   <padding>
      <Insets bottom="16.0" left="16.0" right="16.0" top="16.0" />
   </padding>
</VBox>

回答by ItachiUchiha

Resize Issue

调整问题

Make sure you are adding a size to your JFrame

确保您正在为您的尺寸添加尺寸 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

我不确定您是否正在考虑将框架或 JavaFX 控件居中GridPane,因此我正在为它们添加答案

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

截屏

GridPaneChild Centering

GridPane儿童居中

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

在此处输入图片说明