更改标签文本javafx-fxml

c3frrgcw  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(386)

这是我的主要课程:

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;
    }
}

这是我的窗口:

<?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(),如下所示:

public class MyClass {
public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        MainController.initialize();
    }
}
}

但是有nullpointerexception。有人能帮我吗?

kkbh8khc

kkbh8khc1#

只需删除字段和方法的static,然后在main类中通过main()运行应用程序:

public class MainController {
    @FXML
    private Label aaa;

    @FXML
    public void initialize(){
        aaa.setText("AHOJ");
    }
}

相关问题