我正在使用 JavaFX 中的 MediaPlayer 类制作一个随着歌曲播放而移动的 slider 。这工作得很好, slider 随着歌曲移动。如果拖动 slider ,它会更改歌曲的位置(使用 .seek() 方法)。当我单击 slider 时出现唯一的问题。歌曲没有移动,我认为这是因为听者看着歌曲的位置仍在继续,这会将 slider 移动到下一个位置。我认为这阻止了用户的点击,但我不确定如何修复它。这是否意味着暂停监听器或我不确定的事情?
protected void updateValues() {
if (playTime != null && progressBar != null && volume != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = player.getCurrentTime();
duration = player.getMedia().getDuration();
playTime.setText(formatTime(currentTime, duration));
progressBar.setDisable(duration.isUnknown());
if (!progressBar.isDisabled()
&& duration.greaterThan(Duration.ZERO)
&& !progressBar.isValueChanging()) {
progressBar.setValue(currentTime.divide(duration).toMillis()
* 100.0);
}
}
});
}
}
progressBar.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
player.seek(duration.multiply(progressBar.getValue()/100.0));
}
});
如果有帮助,我已经关注了:https://docs.oracle.com/javafx/2/media/playercontrol.htm
最佳答案
我怀疑您需要添加 setOnMouseClicked单击鼠标即可触发事件,
progressBar.setOnMouseClicked(e ->
player.seek(duration.multiply(progressBar.getValue()/100.0))
);
如果您想使用鼠标事件来实现这两种情况,则可能需要添加两个鼠标事件处理程序 setOnMouseReleased
(用于拖动并释放 slider )和 setOnMouseClicked
(用于单击 slider )。但我建议你添加一个ChangeListener到您的 slider ,而不是设置鼠标事件监听器。
progressBar.valueProperty().addListener((observable, oldValue, newValue) ->
player.seek(duration.multiply(newValue.doubleValue()/100.0))
);
关于java - 事件监听器妨碍更改 slider 值 JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923466/