我是一个javafx初学者,正在学习fxml
实践中控件startButton总是为null,这是为什么?求指教!
java:
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.control.*;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/appilcation/welcome_scene.fxml"));
loader.setController(this);
Scene scene = new Scene(loader.load(),640,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
welcome();
}
@FXML
Button startButton;
public static void main(String[] args) {
launch(args);
}
public void welcome() {
startButton.setOnAction(e -> {
System.out.println(1);
});
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
<children>
<AnchorPane maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
<children>
<Label alignment="CENTER" layoutX="149.0" layoutY="36.0" style=" " text="MPCB_STAR_WARS" textAlignment="CENTER" textFill="#9f9f9f" wrapText="false">
<font>
<Font size="37.0" />
</font>
</Label>
<Button fx:id="startButton" layoutX="409.0" layoutY="107.0" mnemonicParsing="false" prefHeight="47.0" prefWidth="142.0" text="START_GAME" />
<Button layoutX="409.0" layoutY="189.0" mnemonicParsing="false" prefHeight="47.0" prefWidth="142.0" text="SETTING" />
<Button layoutX="409.0" layoutY="270.0" mnemonicParsing="false" prefHeight="47.0" prefWidth="142.0" text="HELP" />
</children>
</AnchorPane>
</children>
</VBox>