【问题标题】:How to show elements on FXML file loaded in JavaFX application?如何在 JavaFX 应用程序中加载的 FXML 文件中显示元素?
【发布时间】:2019-02-15 20:54:01
【问题描述】:


我需要了解如何显示由 Main javaFX 应用程序加载的 FXML 文件中插入的元素,我的 JavaFX 应用程序主要是:

// imports omitted
public class Main extends Application {
@Override
public void start(Stage window) throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("Standard.fxml"));
    Scene mainGraphic = new Scene(root,500,500);

    window.setTitle("Prova con FXML");
    window.setMinHeight(500);
    window.setMinWidth(500);
    window.setScene(mainGraphic);
    window.show();
    }
}

这个文件可以正常加载FXML文件Standard.fxml,问题是它没有显示顶部矩形,这是FXML文件:

// imports omitted    
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.myname.mypackage.Controller">
    <stylesheets>
        <URL value="@Standard.css"/>
    </stylesheets>

    <Rectangle id="ParteSuperiore"/>
</AnchorPane>

我显然已经创建了 CSS 文件并使用我想要的属性对元素进行了样式化,这就是 CSS:

#AnchorPane {
    -fx-background-color: rgb(224, 246, 255);
}

#ParteSuperiore {
    -fx-fill: rgb(255, 145, 28);
    -fx-arc-height: 100px;
    -fx-arc-width: 100px;
}

这个文件有什么问题?我只能看到 AnchorPane 的背景颜色!我试图将Rectangle 放在&lt;children&gt; 元素中,但是我继续只看到AnchorPane 的背景颜色,而看不到矩形!我应该使用区域而不是矩形吗?如果是,我怎样才能给它宽度和高度?在JavaFX CSS reference 中,它没有给我设置宽度和高度的指令,比如矩形的-fx-arc-height

【问题讨论】:

    标签: java css javafx fxml


    【解决方案1】:

    您似乎混淆了arcHeight/arcWidth 属性和height/width 属性Rectangle。根据文档,arcHeight 属性:

    定义矩形四个角处圆弧的垂直直径。当且仅当弧宽和弧高属性都大于0.0 时,矩形才会有圆角。

    还有height 属性:

    定义矩形的高度。

    arcWidthwidth 属性具有相似的文档。

    widthheight 属性的默认值都是 0.0。由于您没有为Rectangle 定义宽度或高度,因此无需渲染任何内容。查看JavaFX CSS Reference GuideRectangle 文档以及ShapeNode,无法从CSS1 设置Rectangle 的宽度或高度。您需要在代码或 FXML 文件中执行此操作。例如:

    // imports omitted    
    <AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.myname.mypackage.Controller">
        <stylesheets>
            <URL value="@Standard.css"/>
        </stylesheets>
    
        <Rectangle id="ParteSuperiore" width="100" height="100"/>
    
    </AnchorPane>
    

    您可能希望删除或至少更改 CSS 文件中的 -fx-arc-width-fx-arc-height 值。


    1.查看implementation 证实了这一点。 widthheight 都不是 StyleableProperty 的实例,不像 arcWidtharcHeight

    【讨论】:

    • 通过从 FXML 给出高度和宽度,它需要以 px 为单位的大小,是否可以在这些字段中以百分比给出大小(尝试它会导致我出错)?
    • 不直接,不。通过代码或 FXML 设置宽度和高度使用像素。不过,您可以尝试使用 expression bindings 来发挥自己的优势(或者如果在代码中则只是绑定)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2014-02-03
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多