SAE21_2023/src/MusicButton.java

48 lines
1.6 KiB
Java
Raw Normal View History

import javax.swing.*;
/**
* It provides a button that toggles between playing and stopping music when clicked.
* @version 1.0
* @author Moncef STITI
* @author Marco ORFAO
*/
2024-04-09 23:28:32 +02:00
public class MusicButton extends JButton {
private static MusicPlayer currentMusicPlayer;
private ImageIcon iconOn;
private ImageIcon iconOff;
private MusicPlayer musicPlayer;
/**
* Constructs a MusicButton.
* @param onIconPath The file path for the icon when music is on.
* @param offIconPath The file path for the icon when music is off.
* @param musicFilePath The file path for the music file to be played.
*/
public MusicButton(String onIconPath, String offIconPath, String musicFilePath) {
2024-04-08 14:43:35 +02:00
this.iconOn = new ImageIcon(onIconPath);
this.iconOff = new ImageIcon(offIconPath);
setIcon(this.iconOff);
2024-04-09 23:28:32 +02:00
// Vérifie s'il y a déjà une musique en cours de lecture et l'arrête si nécessaire
if (currentMusicPlayer != null && currentMusicPlayer.isPlaying()) {
currentMusicPlayer.stop();
currentMusicPlayer = null;
}
2024-04-08 14:43:35 +02:00
this.musicPlayer = new MusicPlayer(musicFilePath);
addActionListener(e -> {
2024-04-09 23:28:32 +02:00
if (currentMusicPlayer != null && currentMusicPlayer.isPlaying()) {
currentMusicPlayer.stop();
currentMusicPlayer = null;
2024-04-08 14:43:35 +02:00
setIcon(this.iconOff);
} else {
2024-04-08 14:43:35 +02:00
this.musicPlayer.play();
setIcon(this.iconOn);
2024-04-09 23:28:32 +02:00
currentMusicPlayer = this.musicPlayer;
}
});
}
}