You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX MediaPlayer项目addListener报错:未找到合适方法

Fixing "No suitable method found for addListener" with JavaFX MediaPlayer's currentTimeProperty

Hey there, let's sort out this error you're hitting with your JavaFX MediaPlayer code. The root of the problem is super straightforward—you've got a mismatch between two different Duration classes that look identical but belong to completely separate packages.

What's causing the error?

JavaFX's MediaPlayer.currentTimeProperty() is designed to work with javafx.util.Duration, but your ChangeListener is using java.time.Duration (the standard Java 8+ date/time API class). These are distinct types, so the compiler can't find a valid addListener() method that accepts your anonymous ChangeListener<java.time.Duration> instance.

How to fix it

You've got two simple solutions:

  1. Correct your import statement
    Check the top of your Java file—if you see import java.time.Duration;, replace it with:

    import javafx.util.Duration;
    

    This ensures all references to Duration in the file use the JavaFX-specific version that matches the MediaPlayer API.

  2. Explicitly qualify the Duration class
    If you need to use both java.time.Duration and javafx.util.Duration in the same file (for example, handling both media timing and date logic), just specify the full package name for the JavaFX version in your ChangeListener:

    mediaPlayer.currentTimeProperty().addListener(new ChangeListener<javafx.util.Duration>() { 
        @Override 
        public void changed(ObservableValue<? extends javafx.util.Duration> observable, javafx.util.Duration oldValue, javafx.util.Duration newValue) { 
            // Replace the throw statement with your actual logic, like updating a progress bar
            // Example:
            // double progress = newValue.toSeconds() / mediaPlayer.getMedia().getDuration().toSeconds();
            // progressSlider.setValue(progress);
        } 
    });
    

Quick tip

JavaFX has its own set of utility classes for media and UI tasks, so always double-check your imports when working with MediaPlayer, Timeline, or other JavaFX components—mixing up standard Java API classes with JavaFX-specific ones is a super common gotcha!

内容的提问来源于stack exchange,提问作者Raysur Rahman Rabby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:09:17