问题
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