JavaFX MediaPlayer项目addListener报错:未找到合适方法
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:
Correct your import statement
Check the top of your Java file—if you seeimport java.time.Duration;, replace it with:import javafx.util.Duration;This ensures all references to
Durationin the file use the JavaFX-specific version that matches the MediaPlayer API.Explicitly qualify the Duration class
If you need to use bothjava.time.Durationandjavafx.util.Durationin 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

