事件侦听器妨碍更改滑块值JavaFX

问题描述 投票:0回答:1

我正在使用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

java javafx slider listener
1个回答
0
投票

我怀疑您需要添加setOnMouseClicked才能通过鼠标单击触发事件,

progressBar.setOnMouseClicked(e -> 
    player.seek(duration.multiply(progressBar.getValue()/100.0))
);

[如果要同时使用鼠标事件来处理这两种情况,则可能需要添加两个鼠标事件处理程序setOnMouseReleased(用于拖动和释放滑块)和setOnMouseClicked(用于单击滑块)。但是我建议您在滑块上添加ChangeListener,而不要设置鼠标事件监听器。

progressBar.valueProperty().addListener((observable, oldValue, newValue) ->
    player.seek(duration.multiply(newValue.doubleValue()/100.0))
);
© www.soinside.com 2019 - 2024. All rights reserved.