【发布时间】:2017-09-14 17:56:05
【问题描述】:
我正在使用 SceneBuilder 在 JavaFX 中创建一个基本的游戏启动器。由于 SceneBuilder 在 FXML 中工作,因此我的启动器布局在 FXML 中。我的主类中有一个方法,我想在单击按钮时调用它。我读到你可以使用
#methodName
在按钮的
onAction
属性,但这不起作用。
我的主要 Java 类:
@FXML
private void launchGame(ActionEvent e) {
System.out.println("Launching...");
}
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(Main.class.getResource("launcher.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("First Week Login");
primaryStage.setResizable(false);
primaryStage.sizeToScene();
primaryStage.show();
}
我的 FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.text.Text?>
<?import javafx.scene.web.WebView?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/8.0.102">
<children>
<BorderPane prefHeight="493.0" prefWidth="664.0" styleClass="background"
stylesheets="@launcher.css">
<bottom>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0"
BorderPane.alignment="CENTER">
<children>
<Button alignment="CENTER" mnemonicParsing="false"
text="Launch Game" onAction="#launchGame" />
</children>
</HBox>
</bottom>
<top>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0"
BorderPane.alignment="CENTER">
<children>
<Text strokeType="OUTSIDE" strokeWidth="0.0"
styleClass="title" text="First Week" />
</children>
</HBox>
</top>
<center>
<WebView prefHeight="200.0" prefWidth="200.0"
BorderPane.alignment="CENTER" />
</center>
</BorderPane>
</children>
</AnchorPane>
【问题讨论】:
-
您不需要直接编辑 FXML 文件。 SceneBuilder 允许您指定控制器、组件 ID 和操作。您是否通过 SceneBuilder 指定了操作?
-
不,我没有,我是在 Eclipse 中写入的
-
对不起,我误读了您的评论。绝对应该为此使用 SceneBuilder。在使用 SceneBuilder 时,您几乎不必直接编辑 FXML 文件。
-
SceneBuilder 也可以为控制器生成框架代码,一旦你添加了
fx:ids 和事件处理程序,并指定了一个控制器类。转到菜单上的“查看”并选择“显示骨架控制器代码”。然后您可以将控制器代码复制并粘贴到您的 IDE 中(控制器必须在 IDE 中编辑,而不是在 SceneBuilder 中)。