我遇到了一个问题,我很难找到解决方法。我有一个HtmlEditor事件,它检测何时按下了一个键,但是我需要创建一个侦听器来检查HtmlEditor文本是否已更改,并且我想到了这一点:
htmlEditor.setOnKeyPressed((keyEvent) ->{
if(keyEvent.getCode().isDigitKey() || keyEvent.getCode().isLetterKey() ||
keyEvent.getCode().isModifierKey() || keyEvent.getCode().isWhitespaceKey() ||
keyEvent.isShiftDown()){
handleWhoTypes(null);
}
});
PauseTransition timer = new PauseTransition(Duration.seconds(5));
htmlEditor.textProperty().addListener((obs, oldText, newText) ->
timer.playFromStart());
timer.setOnFinished(e -> handleIsPaused(null));
}
但这是行不通的,因为htmlEditor没有textProperty(),而且我想不出另一种解决方案。先感谢您。
最佳答案
看来您必须轮询编辑器的文本:
Runnable textMonitor = new Runnable() {
private String previousText;
@Override
public void run() {
String newText = htmlEditor.getHtmlText();
boolean changed = !newText.equals(previousText);
previousText = newText;
if (changed) {
timer.playFromStart();
}
}
};
BooleanBinding windowShowing = Bindings.selectBoolean(
htmlEditor.sceneProperty(), "window", "showing");
windowShowing.addListener(
new ChangeListener<Boolean>() {
private ScheduledExecutorService executor;
@Override
public void changed(ObservableValue<? extends Boolean> o,
Boolean old,
Boolean showing) {
if (showing) {
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(
() -> Platform.runLater(textMonitor),
1, 1, TimeUnit.SECONDS);
} else {
executor.shutdown();
}
}
});