還有就是我的主類:更改標籤文本的JavaFX FXML
public class Main extends Application {
private static Stage primaryStage;
public static BorderPane mainLayout;
@Override
public void start(Stage primaryStage) {
this.setPrimaryStage(primaryStage);
primaryStage.setTitle("Project");
try {
mainLayout =
FXMLLoader.load(Main.class.getResource("/main/view/MainPage.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(mainLayout);
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
System.exit(0);
}
});
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static Stage getPrimaryStage() {
return primaryStage;
}
public void setPrimaryStage(Stage primaryStage) {
Main.primaryStage = primaryStage;
}
}
我窗口的這個FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<BorderPane prefHeight="410.0" prefWidth="512.0"
xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="main.controller.MainController">
<center>
<VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0"
spacing="20.0" BorderPane.alignment="CENTER">
<children>
<Label fx:id="aaa" prefHeight="72.0" prefWidth="336.0"
text="Project" textAlignment="CENTER">
<font>
<Font name="Century Gothic" size="25.0" />
</font>
</Label>
</children>
<padding>
<Insets bottom="30.0" />
</padding>
</VBox>
</center>
</BorderPane>
這是控制器的這種FXML:
public class MainController {
@FXML
private static Label aaa;
@FXML
public static void initialize(){
aaa.setText("AHOJ");
}
}
我想從另一個類調用方法initialize()10次,如下所示:
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
MainController.initialize();
}
}
}
但存在NullPointerException。有人能幫我嗎?
你有NPE,因爲你的靜態字段不被初始化。循環的最終目標是什麼? –
這是例子。我的目標是通過從另一個班級調用方法來更新標籤文本,但只是一次,但我不知道如何。 –
其他課程是什麼?這是一個FX應用程序,通過main()方法運行,並在單獨的線程中運行。你打算從哪個班改變一個標籤? –