该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.applet.AudioClip;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JFileChooser;
import java.net.URL;
public class aa extends JFrame implements ActionListener{
AudioClip adc;//声音音频剪辑对象
JLabel la=new JLabel();
JLabel pn1=new JLabel();
File file;
String fileName;
boolean loop=false;//判定是否循环操作
JFileChooser chooser=new JFileChooser();//创建一个选择器对象
public aa() {
super("音乐播放器");
JButton[] bn=new JButton[3];
JPanel pn=new JPanel(new GridLayout());//创建面板 pn
Icon[] ic=new Icon[3];
for(int i=0;i
ic[i]=new ImageIcon("C:\\Users\\a1997\\Desktop\\image\\"+(i+1)+".png");
}
bn[0]=new JButton("开始",ic[0]);
bn[0].addActionListener(this);//添加事件的监听
bn[1]=new JButton("停止",ic[1]);
bn[1].addActionListener(this);//添加事件的监听
bn[2]=new JButton("循环",ic[2]);
bn[2].addActionListener(this);//添加事件的监听
pn.add(bn[0],0);//将开始按钮添加到面板pn第一个位置
pn.add(bn[1],1);
pn.add(bn[2],2);
this.add(pn,BorderLayout.SOUTH);
//创建菜单
JMenu fileMenu=new JMenu("文件");
JMenuItem openMenuItem=new JMenuItem("打开");
openMenuItem.addActionListener(this);
fileMenu.add(openMenuItem);
fileMenu.addSeparator();//分割线
JMenuItem exitMenuItem=new JMenuItem("退出");
exitMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
JMenuBar menuBar=new JMenuBar();
menuBar.add(fileMenu);
String flag="欢迎光临";
this.setFrame(flag);
this.setJMenuBar(menuBar);
this.setSize(300,360);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("退出")) {
dispose();
return ;
}
if(e.getActionCommand().equals("打开")) {
int val=chooser.showOpenDialog(this);
if(val==chooser.APPROVE_OPTION) {
file=chooser.getSelectedFile();
fileName=file.getName();
String flag="您正在听:"+fileName;
this.setFrame(flag);
try {
URL url=new URL("file:"+file.getPath());//创建资源定位
adc=JApplet.newAudioClip(url);//为adc赋值
adc.play();//开始播放
}catch(MalformedURLException e1) {
e1.printStackTrace();
System.out.println("不能播放");
}
}
}
if(e.getActionCommand().equals("开始")) {
String flag="您正在听:"+fileName;
if(adc==null) {
flag="请选择播放文件哦!";
this.setFrame(flag);
return ;
}
adc.play();
this.setFrame(flag);
}
if(e.getActionCommand().equals("停止")) {
adc.stop();
String flag="停止播放"+fileName;
this.setFrame(flag);
}
if(e.getActionCommand().equals("循环")) {
loop=!loop;
String flag="";
if(loop) {
adc.play();
adc.loop();
flag="循环播放:"+fileName;
}
else {
adc.play();
flag="顺序播放"+fileName;
}
this.setFrame(flag);
}
}
/*
* 提取公共部分
*/
public void setFrame(String flag) {
la.setText(flag);
pn1.add(la,0);
this.add(pn1,FlowLayout.CENTER);
}
public static void main(String[] args) {
new aa();
}
}