我正在使用JavaFX的MediaPlayer类制作一个滑动条,它会随着歌曲的播放而移动。这完全没问题,滑块随着歌曲移动。如果拖动滑块,它会改变歌曲的位置(使用。seek()方法)。唯一的问题发生在我点击滑块的时候。歌曲没有移动,我认为这是因为听众仍然在看歌曲的位置,这是将滑块移动到下一个位置。我认为这阻碍了用户的点击,但我不确定如何修复它。这是否意味着暂停听众或其他我不确定的事情?
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
我怀疑您需要添加setOnMouseClickd以在鼠标单击时触发事件,
progressBar.setOnMouseClicked(e ->
player.seek(duration.multiply(progressBar.getValue()/100.0))
);
如果您想使用mouse-event来处理这两种情况,您可能需要添加两个鼠标事件处理程序< code>setOnMouseReleased(用于拖动并释放滑块)和< code>setOnMouseClicked(用于单击滑块)。但是我建议您在滑块中添加一个ChangeListener,而不是设置鼠标事件侦听器。
progressBar.valueProperty().addListener((observable, oldValue, newValue) ->
player.seek(duration.multiply(newValue.doubleValue()/100.0))
);