我对java还很陌生。我想使用类更新按钮的文本,以便在调用该方法时它会相应更新。我尝试实现其他相关帖子中的一些代码,但无法弄清楚。首先 - 你是否必须更新整个场景才能更新按钮,或者它的工作方式是否像 React 一样更新部分 DOM?
目标是在场景加载时更新按钮的文本。 FXML 文件:
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="project.Controller">
<Button fx:id="button" text="STOP"></Button>
</AnchorPane>
主要 Java 文件:
public class project extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(project.class.getResource("index.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root, 1200, 750);
primaryStage.setScene(scene);
primaryStage.show();
Controller editButton = new Controller();
editButton.editButtonText("blabla selected");
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
launch(args);
}
}
类文件:
public class Controller implements Initializable
{
//FXML
@FXML public Button button;
@FXML
public void editButtonText(String text){
// button = new Button();
button.setText(text);
}
@Override
public void initialize(URL url, ResourceBundle r){
}
}
最佳答案
Controller editButton = new Controller();
editButton.editButtonText("blabla selected");
问题出在那个部分。使用 FXMLLoader 加载 fxml 文件后,会自动创建一个新的 Controller 对象。您可以使用访问该 Controller 对象
Controller editButton = (Controller) loader.getController`
否则,您将引用一个新的 Controller ,该 Controller 没有分配给它的 GUI。
或者,您也可以将其写为:
Controller controller = new Controller();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(project.class.getResource("index.fxml"));
loader.setController(controller);
Parent root = loader.load()
这样,您新创建的 Controller 对象将被设置为您要加载的 fxml 文件的 FXMLController。 注意:要实现此功能, Controller 不能在 fxml 文件中设置。
关于java - 如何在 java 中使用 setText 更新 FXML 按钮 - 当它返回 java.lang.NullPointerException 错误时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59028629/