我正在大学学习编程,现在是第二年,我正在开始使用 java fxml 场景生成器。我知道基础知识以及如何将代码与 @FXML 等连接起来。但我有一个大问题。所以,我基本上创建了我的窗口,一些组合框等,但是代码 java scene buildergeneretes 带有错误,我无法编译。我将向您展示代码:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="582.0" prefWidth="804.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="lab001.InterFaceGraficaController">
<children>
<Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" />
<Label layoutX="64.0" layoutY="363.0" text="Label" />
<Label layoutX="64.0" layoutY="199.0" text="Label" />
<Label layoutX="64.0" layoutY="412.0" text="Label" />
<Label layoutX="47.0" layoutY="59.0" text="Label" />
<Button id="a" layoutX="115.0" layoutY="508.0" mnemonicParsing="false" onAction="#adicionar" text="add" />
<Button layoutX="229.0" layoutY="510.0" mnemonicParsing="false" onAction="#limpar" text="limpar" />
<ComboBox fx:id="combo" layoutX="111.0" layoutY="410.0">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Item 1" />
<String fx:value="Item 2" />
<String fx:value="Item 3" />
</FXCollections>
</items>
</ComboBox>
<TextArea fx:id="txtA" layoutX="121.0" layoutY="114.0" prefWidth="200.0" wrapText="true" />
<Slider fx:id="sl" blockIncrement="1.0" layoutX="121.0" layoutY="365.0" majorTickUnit="2.0" max="10.0" min="1.0" minorTickCount="1" showTickLabels="true" showTickMarks="true" snapToTicks="true" value="0.0" />
<ListView fx:id="filmes" layoutX="539.0" layoutY="152.0" prefHeight="200.0" prefWidth="200.0" />
<TextField fx:id="txt" layoutX="100.0" layoutY="56.0" prefWidth="200.0" />
</children>
</AnchorPane>
我收到如下错误:JavaFX.scene.layout.anchorpane 不支持属性 Controller 。
这是一些 jdk 相关的错误吗?因为这是纯粹自动生成的代码,所以我没有接触过它。
最佳答案
我刚刚复制了你的整个FXML并在相应的包中编写了相应的Controller并得到了这个结果:http://puu.sh/4uZsk.png
如何复制:
- 创建新的 FXML 项目(确保您的 ClassPath 中包含 JavaFX Lib,否则您需要使用 Java 8)
- 创建新包
lab001
- 使用此内容创建一个名为
Main.java
的新类
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(this.getClass().getResource("application.fxml"));
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
- 使用此内容创建一个名为
InterFaceGraficaController
的新类
public class InterFaceGraficaController {
@FXML Label label;
@FXML ComboBox<String> combo;
public InterFaceGraficaController() {
System.out.println("init");
}
@FXML private void adicionar() {}
@FXML private void limpar() {}
}
并添加您给定的 FXML, 如果您仍然收到错误,您需要粘贴您的错误日志并编辑您的帖子以显示您的进度。
编辑:只是为了确定;您的 Controller 必须具有您在SceneBuilder中添加的功能,否则它无法像您的情况中的adicionar
一样绑定(bind)它们。
关于java FXML 生成的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18855897/