我使用SceneBuilder在JavaFX中创建基本游戏启动器。由于SceneBuilder在FXML中工作,我的启动程序布局在FXML中。我在我的主类中有一个方法,我想调用一个按钮单击。我读了你可以使用按钮单击Java Java 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中写入它 – JPadley
对不起,我误解了你的评论。应该肯定使用SceneBuilder。在使用SceneBuilder时,几乎不需要直接编辑FXML文件。 –