简体   繁体   English

JavaFX-如何将ChangeListener添加到与其他类的StringProperty绑定的TextArea

[英]JavaFX - how to add ChangeListener to TextArea binded with StringProperty from other class

I have a main class where I have TextArea showing some logs of my program. 我有一个主类,其中有TextArea,它显示程序的一些日志。 It looks like this: 看起来像这样:

@FXML
private TextArea eventLog;

I need to access it from other classess (scenes), so it's binded with StringProperty like this: 我需要从其他类(场景)访问它,因此它与StringProperty绑定,如下所示:

eventLog.textProperty().bind(LogInfo.logDataProperty());

LogInfo looks like this: LogInfo看起来像这样:

public class LogInfo {

private static StringProperty logData = new SimpleStringProperty();

public static void setLogData(String data) {
        logData.set(getLogData() + data);
    }

}

setLogData is basicly copying all infomations already stored on TextArea eventLog and adding new line. setLogData基本上是复制已经存储在TextArea eventLog上的所有信息,并添加新行。 It's working fine, but here comes my problem: 一切正常,但是我的问题来了:

TextArea doesn't scroll when new informations are shown. 显示新信息时,TextArea不滚动。 I need to add ChangeListener to my eventLog textArea like this: 我需要像这样将ChangeListener添加到我的eventLog textArea中:

eventLog.textProperty().addListener(new ChangeListener<Object>() {
        @Override
        public void changed(ObservableValue<?> observable, Object oldValue,
                Object newValue) {
            eventLog.setScrollTop(Double.MAX_VALUE); 
        }
    });

It doesn't work, because informations are added by setLogData from LogInfo class, not from eventLog TextArea directly. 它不起作用,因为信息是通过setLogData从LogInfo类添加的,而不是直接从eventLog TextArea添加的。 So I need to implement ChangeListener on my LogInfo class, but the problem is that I can't control eventLog TextArea from LogInfo class. 因此,我需要在LogInfo类上实现ChangeListener,但问题是我无法从LogInfo类控制eventLog TextArea。 Is there any way to make something like reverse binding from this class ? 有什么办法可以从此类中进行诸如反向绑定之类的操作吗?

您需要对属性进行双向绑定,有关更多信息, 请参见此较早的帖子

Bind the listener directly to the LogInfo property instead of binding it to the TextArea property: 将侦听器直接绑定到LogInfo属性,而不是将其绑定到TextArea属性:

Main.logDataProperty().addListener((observable, oldValue, newValue) -> {
            textArea.setScrollTop(Double.MAX_VALUE);
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM