繁体   English   中英

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

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

我有一个主类,其中有TextArea,它显示程序的一些日志。 看起来像这样:

@FXML
private TextArea eventLog;

我需要从其他类(场景)访问它,因此它与StringProperty绑定,如下所示:

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

LogInfo看起来像这样:

public class LogInfo {

private static StringProperty logData = new SimpleStringProperty();

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

}

setLogData基本上是复制已经存储在TextArea eventLog上的所有信息,并添加新行。 一切正常,但是我的问题来了:

显示新信息时,TextArea不滚动。 我需要像这样将ChangeListener添加到我的eventLog textArea中:

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

它不起作用,因为信息是通过setLogData从LogInfo类添加的,而不是直接从eventLog TextArea添加的。 因此,我需要在LogInfo类上实现ChangeListener,但问题是我无法从LogInfo类控制eventLog TextArea。 有什么办法可以从此类中进行诸如反向绑定之类的操作吗?

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

将侦听器直接绑定到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