我希望根据某个值更新文本字段中的文本。为了使这个示例更简单,我缩小了我的程序。问题似乎是当我放置 top.setText("This is my new Text"); 时
我看了这个:如何更改java fx 2中TextField的文本 https://stackoverflow.com/questions/10601648/how-to-change-the-text-of-textfield-in-java-fx-2
但答案似乎没有意义。我不知道为什么你要初始化一个已经实现的文本字段。不管怎样,它没有起作用。
我也看过:NullPointerException(JavaFX Label.setText()) https://stackoverflow.com/questions/22145327/nullpointerexception-javafx-label-settext
这似乎最接近我认为的问题,但是当我执行以下操作时,我收到错误。为了清楚起见,它位于 JavaFXApplication5 类中。
try {
FXMLLoader loader = new FXMLLoader(
getClass().getResource("FXML.fxml")
);
FXMLLoader.setController(this); // non-static method setController(Object)
// can not be referenced from static context ERROR****
Parent root = (Parent) loader.load();
/*Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("java code");
stage.show();
*/
}
通过在互联网上阅读,我想知道是否存在竞争条件:http://gotoanswer.stanford.edu/nullpointerexception_in_javafx_initialize_method-8807679/ http://gotoanswer.stanford.edu/nullpointerexception_in_javafx_initialize_method-8807679/
所以我尝试:
Platform.runLater(new Runnable() {
@Override public void run() {
top.setText("This is my new Text");
}
});
但这没有用。我知道它可以在场景生成器中设置,但我需要一种方法来根据另一个类的值动态更改它。如果我能弄清楚如何开始设置它,我就能弄清楚如何完成该部分。希望这足以解释以获得一些帮助。
FXMLController Class:
public class FXMLController implements Initializable {
@FXML private TextField top;
public FXMLController() {
System.out.println("Hi");
top.setText("This is my new Text"); // This breaks the program *********
}
@Override
public void initialize(URL url, ResourceBundle rb) {
}
}
FXML.fxml class:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="javafxapplication5.FXMLController">
<children>
<TextField fx:id="top" layoutX="171.0" layoutY="68.0" />
</children>
</AnchorPane>
JavaFXApplication5 class: // main class
public class JavaFXApplication5 extends Application {
@Override
public void start(Stage stage) throws Exception {
try {
Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("java code");
stage.show();
}
catch (Exception ex) {
Logger.getLogger(JavaFXApplication5.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
launch(args);
}
}