java swing 完整音乐播放器
时间: 2023-09-08 08:11:29 浏览: 153
以下是一个简单的 Java Swing 音乐播放器的示例代码:
```java
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
public class MusicPlayer extends JFrame {
private JPanel contentPane;
private JLabel lblSongName;
private JButton btnPlay;
private JButton btnPause;
private JButton btnStop;
private JFileChooser fileChooser;
private BasicPlayer player;
private File currentFile;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MusicPlayer frame = new MusicPlayer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MusicPlayer() {
setTitle("Music Player");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
lblSongName = new JLabel("No song selected");
lblSongName.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblSongName, BorderLayout.NORTH);
JPanel buttonPane = new JPanel();
contentPane.add(buttonPane, BorderLayout.CENTER);
btnPlay = new JButton("Play");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
playSong();
}
});
buttonPane.add(btnPlay);
btnPause = new JButton("Pause");
btnPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pauseSong();
}
});
buttonPane.add(btnPause);
btnStop = new JButton("Stop");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopSong();
}
});
buttonPane.add(btnStop);
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
player = new BasicPlayer();
}
private void playSong() {
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
currentFile = fileChooser.getSelectedFile();
lblSongName.setText(currentFile.getName());
try {
player.open(currentFile);
player.play();
} catch (BasicPlayerException e) {
e.printStackTrace();
}
}
}
private void pauseSong() {
try {
player.pause();
} catch (BasicPlayerException e) {
e.printStackTrace();
}
}
private void stopSong() {
try {
player.stop();
player.close();
lblSongName.setText("No song selected");
} catch (BasicPlayerException e) {
e.printStackTrace();
}
}
}
```
这个示例使用了 `javax.swing` 和 `javazoom.jlgui.basicplayer` 库。基本的播放器控件是 `JLabel` 和三个 `JButton`,分别用于选择和播放音乐,暂停和继续播放音乐,以及停止播放音乐。播放器使用 `BasicPlayer` 类来实现音乐播放。
阅读全文