JavaFX update textArea

痴心易碎 提交于 2019-12-22 08:23:11

问题


I have a simple JavaFX application which has a TextArea. I can update the content of the textArea with the code below inside the start() method:

new Thread(new Runnable() {

    public void run() {

        for (int i = 0; i < 2000; i++) { 

            Platform.runLater(new Runnable() {
                public void run() {
                    txtarea.appendText("text\n");
                }
            });
        }
    }
}).start();

The code just write the text string into the TextArea 2000 times. I want to update this textArea from a function which is implemented outside of the start() method.

public void appendText(String p){
    txtarea.appendText(p);
}

This function can be called from arbitrary programs which use the JavaFX application to update the TextArea. How can I do this inside the appendText function?


回答1:


You could give the class which needs to write to the javafx.scene.control.TextArea an reference to your class which holds the public void appendText(String p) method and then just call it. I would suggest you also pass an indication from which class the method was called, e.g.:

public class MainClass implements Initializable {
    @FXML
    private TextArea txtLoggingWindow;
    [...more code here...]
    public void appendText(String string, String string2) {
       txtLoggingWindow.appendText("[" + string + "] - " + string2 + "\n");
    }
}

public class SecondClass {
    private MainClass main;
    public SecondClass(MainClass mClass) {
        this.main = mClass;
    }
    public void callMainAndWriteToArea() {
        this.main.appendText(this.getClass().getCanonicalName(), "This Text Goes To TextArea");
    }
}


来源:https://stackoverflow.com/questions/18597644/javafx-update-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!