简体   繁体   中英

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. 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:

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

LogInfo looks like this:

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. It's working fine, but here comes my problem:

TextArea doesn't scroll when new informations are shown. I need to add ChangeListener to my eventLog textArea like this:

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. So I need to implement ChangeListener on my LogInfo class, but the problem is that I can't control eventLog TextArea from LogInfo class. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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