Java FXML调用方法按钮点击



我正在使用SceneBuilder在Javafx中创建一个基本的游戏启动器。由于Scene -Builder在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>

您需要创建一个单独的控制器类,并用fx:controller="packageName.Classname"

在顶部AnchorPane标记中指定它。

这样:

<AnchorPane xmlns:fx="http://javafx.com/fxml/1"
 xmlns="http://javafx.com/javafx/8.0.102"
 fx:controller="com.packageName.Controller">

所谓的方法应在指定的控制器类中。

com.packageName只是一个示例,您应该使用包装的名称,如果不在任何软件包中,则将其放置在该软件包中或没有软件包名称。

最新更新