这是按钮的 fxml 标记:
<Button fx:id="btn" layoutX="279.0" layoutY="130.0" mnemonicParsing="false" text="Button" />
舞台运行良好,但我不能使用任何字段,在这种情况下,btn。这就是我加载它的方式:
FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
root = loader.load();
btn.setOnAction(x -> {
System.out.println("button clicked");
});
字段声明如下:
@FXML
Button btn;
来自堆栈跟踪的消息
java.lang.NullPointerException:无法调用“javafx.scene.control.Button.setOnAction(javafx.event.EventHandler)”,因为“this.btn”为空 在 FxmlTest/application.Main.start(Main.java:29)
(Main.java:29 us btn.setOnAction...)
最后,我这样设置控制器:
<AnchorPane fx:id="root" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" **fx:controller="application.Main"**>
我试过的解决方案
root = loader.load();
注意事项
*完整代码
package application;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
@FXML
AnchorPane root;
@FXML
Label basmalaLbl;
@FXML
Button btn;
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
root = loader.load();
btn.setOnAction(x -> {
System.out.println("button clicked");
});
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
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.text.Font?>
<AnchorPane fx:id="root" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Main">
<children>
<Label fx:id="basmalaLbl" layoutX="272.0" layoutY="192.0" text="بسم الله!">
<font>
<Font size="33.0" />
</font>
</Label>
<Button id="btn" fx:id="btn" layoutX="279.0" layoutY="130.0" mnemonicParsing="false" text="Button" />
</children>
</AnchorPane>