簡體   English   中英

更改標簽文本JavaFX FXML

[英]Changing Label text 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()十次,如下所示:

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

但是有NullPointerException。 有人能幫我嗎?

只需刪除字段和方法的靜態變量,然后通過Main類中的main()運行您的應用程序:

public class MainController {
    @FXML
    private Label aaa;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM