首页 > 解决方案 > 为什么这个 JavaFX 应用程序看起来与 SceneBuilder 中的不同?

问题描述

我试图在 JavaFX 上制作我的第一个应用程序,但这让我非常沮丧!应用程序的这些元素在 SceneBuilder 中是完美的,但现在它只是错位了!

在场景生成器中

事实上

我认为这是因为我在运行应用程序时出现了这个错误:

WARNING: Loading FXML document with JavaFX API of version 11.0.1 by JavaFX runtime of version 8.0.231

我试图将 AnchorPane 属性更改为:

<AnchorPane prefHeight="129.0" prefWidth="205.0" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"">
   ...
</AnchorPane>

但它只是修复了警告而不是错位。

这是我的完整代码:

主.java

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.stage.Stage;
import javafx.scene.Scene;
//import javafx.scene.layout.BorderPane;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            //BorderPane root = new BorderPane();
            Parent root = FXMLLoader.load(getClass().getResource("Root.fxml"));
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

根.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="129.0" prefWidth="205.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TextField layoutX="28.0" layoutY="23.0" />
      <Button layoutX="77.0" layoutY="65.0" mnemonicParsing="false" text="Button" />
   </children>
</AnchorPane>

标签: javajavafxscenebuilderefxclipse

解决方案


正如@Slaw 提到的,AnchorPane不是响应式布局。您可以考虑将VBoxCENTER对齐,因为您有两个垂直放置的节点。

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

<?import javafx.geometry.Pos?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>


<VBox prefHeight="129.0"  alignment="CENTER" prefWidth="205.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <TextField fx:id="INPUT_FIELD" />
      <Button fx:id="SUBMIT" mnemonicParsing="false" text="Button" />
   </children>
</VBox>

一般来说,AnchorPane可以设置为父布局,你可以在上面放置VBox,并且可以在VBox上添加控件(Button,TextField等)。

我认为这是因为我在运行应用程序时出现了这个错误:

警告:版本 8.0.231 的 JavaFX 运行时使用版本 11.0.1 的 JavaFX API 加载 FXML 文档

不,这只是一个警告!你可以在这里找到一个巨大的讨论。


推荐阅读