[ad_1]

@Override
public void start(Stage stage) throws Exception {

    MediaPlayer player = new MediaPlayer(<song1 media>);    
    Button b1 = new Button("Song 1");
    b1.setOnAction(playerUpdater(player, <song1 media>));
    Button b2 = new Button("Song 2");
    b2.setOnAction(playerUpdater(MediaPlayer player, <song2 media>));

}
public playerUpdater implements EventHandler<ActionEvent> {
    private MediaPlayer player;
    private final Media media;

    public ChannelUpdater(MediaPlayer player, Media media) {
        this.player = player;
        this.media = media;
    }

    @Override 
    public void handle(ActionEvent event) {
        player.stop();    
        player = new MediaPlayer(media);
        player.play();
    }
}

(I left out stage and scene for the sake of simplicity.) I am trying to write a JavaFX scene where there are multiple buttons that play songs. If I click on Song 1 button, Song 1 should play. But if I click on Song 2, Song 1 doesn’t stop; it just keeps playing simultaneously while Song 2 starts. Song 1 will keep going unless I click Song 1 button again, which only makes it reset. How do I make the player stop playing the previous track altogether and only play the new track?

[ad_2]