【问题标题】:JavaFX text does not change when calling setText() [duplicate]调用 setText() 时 JavaFX 文本不会改变 [重复]
【发布时间】:2019-05-14 23:06:44
【问题描述】:

我正在尝试为网络爬虫创建 GUI。当他们按下搜索按钮时,我希望出现一个显示“正在搜索...”的文本

public class Main extends Application {

    private CrawlerTest c;
    private Scene scene1, scene2;
    private String urls;
    private Text urlsText, searchText;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        this.c = new CrawlerTest();
        primaryStage.setTitle("WebCrawler");



        //layout1
        TextField searchInput = new TextField();
        TextField keyword = new TextField();
        Label searchLabel = new Label("Website URL");
        searchLabel.setLabelFor(searchInput);
        Label keywordLabel = new Label("Search for keyword");
        keywordLabel.setLabelFor(keyword);
        Button searchButton = new Button();
        searchButton.setText("Search!");
        this.searchText = new Text("");
        this.searchText.setFont(new Font(20));
        searchButton.setOnAction(e -> {
            if (this.checkURL(searchInput.getText())) {
                this.searchText.setText("Searching... This may take a while.");
                this.urls = this.c.run(searchInput.getText(), keyword.getText());
                primaryStage.setScene(scene2);
                this.urlsText.setText(this.urls);
            }
            else {
                AlertError.display("Error!", "Entered URL format is incorrect");
            }
        });

        FlowPane container = new FlowPane();
        container.getChildren().addAll(searchInput, keyword, searchButton);
        VBox layout1 = new VBox(10);
        layout1.setPadding(new Insets(20, 20, 20, 20));
        layout1.getChildren().addAll(searchLabel, searchInput, keywordLabel, keyword, this.searchText, searchButton);
        scene1 = new Scene(layout1, 300, 250);

问题是 this.searchText.setText("Searching... This may take a while."); 当它在 if 语句 if (this.checkURL(searchInput.getText())) 中时不会更改文本,但它确实在 if 语句之外工作。当我尝试调试它并且它起作用时,我知道输入了这个 if 语句。单击按钮时,有人可以帮我更改 searchText 的文本吗?谢谢!

【问题讨论】:

  • CrawlerTest.run 是否立即返回?如果这是一个冗长的操作,它会阻止你的 UI 更新,因为它会阻塞 JavaFX 应用程序线程。

标签: java javafx


【解决方案1】:

此条目将对您有所帮助:How do I update Text Using Java.fx?

这是因为你需要使用:

Platform.runLater(() -> {
    textArea.appendText("New text");
});

将所有的 GUI 更新到 Platform.runLater(runnable);方法,这样它就会得到更新。

【讨论】:

  • 直接将此方法应用于问题只会导致Searching... This may take a while. 显示在最后而不是其他文本。实际上解释这个问题并关注这个问题可能已经成为一个不错的答案,但由于你不这样做,它只是一个低质量的答案,可能对 OP 没有什么帮助......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
相关资源
最近更新 更多