17:15:02
Smile。 2017/7/4 17:15:02
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.net
.*;
import com.lzw.MusicPlay;
import com.sun.org
.apache.xpath.internal.functions.FuncBoolean;
import java.applet.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.io
.File;
import java.net
.MalformedURLException;
public class a2 extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JTextField filePath = null;
private JButton openFile = null;
private JButton playButton = null;
private File selectedFile;
private AudioClip audioClip;
private JTextField getJTextField() {
if (filePath == null) {
filePath = new JTextField();
filePath.setPreferredSize(new Dimension(200, 22));
filePath.setEditable(false);
}
return filePath;
}
private JButton getOpenFile(){
if(openFile==null){
openFile=new JButton();//创建“选择文件”按钮
openFile.setText("选择文件");
//添加按钮事件监听器
openFile.addActionListener(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e){
//创建文件选择器对象
JFileChooser fileChooser=new JFileChooser();
//设置文件 过滤
fileChooser.setFileFilter(new FileNameExtensionFilter(
"支持的音频文件(*.mid、*.wav、*.au、*.mp3、*.mp4、*avi", "wav",
"au", "mid","mp3","mp4","avi"));
//显示文件选择对话框
fileChooser.showOpenDialog(a2.this);
//获取选择的文件对象
selectedFile =fileChooser.getSelectedFile();
//在文本框中显示文件信息
filePath.setText(selectedFile.getAbsolutePath());
}
});
}
return openFile;
}
//关于“播放”按钮的方法
private JButton getPlayButton(){
if(playButton ==null){
playButton=new JButton();
playButton.setText("播放");
//添加按钮事件监听器
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// TODO 自动生成的方法存根
if(selectedFile != null){
try{
if(audioClip !=null)
audioClip.stop();
//获取音频剪辑对象
audioClip=Applet.newAudioClip(selectedFile
.toURI().toURL());
audioClip.play();//播放音频
}catch(MalformedURLException e1){
e1.printStackTrace();
}
}
}
});
}
return playButton;
}
public static void main(String[] args) {
MusicPlay thisClass = new MusicPlay();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
public a2() {
super();
initialize();
}
private void initialize() {
this.setSize(408, 79);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new FlowLayout());
jContentPane.add(getJTextField(), null);
jContentPane.add(getOpenFile(), null);
jContentPane.add(getPlayButton(), null);
}
return jContentPane;
}
}