📄 mediaplayer.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.*;
import java.io.*;
import java.net.URL;
import java.util.*;
public class MediaPlayer extends JFrame implements ActionListener,Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JMenuBar bar;//菜单条
private JMenu fileMenu,choiceMenu,aboutMenu;
private JMenuItem openItem,openDirItem,closeItem,about,infor;
private JCheckBoxMenuItem onTop;
private boolean top=false; //设定窗口是否在最前面
private Player player;//Play是个实现Controller的接口
private File file,listFile;//利用File类结合JFileChooser和list.ini进行文件打开等操作操作
private Container c;
private String title;//标题
private FileDialog fd;
private JPanel panel,panelSouth;
private Icon icon; //开始进入的时候要显示的图标,它为抽象类,不能自己创建
private JLabel label,listB;//用来显示图标
private JList list;//播放清单
private JScrollPane scroll;//使播放清单具有滚动功能
private ObjectOutputStream output;//对象输出流
private JPopupMenu popupMenu;//鼠标右键弹出菜单
private JMenuItem del,delAll,reName; //弹出菜单显示的菜单项,包括删除,全部删除和重命名
@SuppressWarnings("unchecked")
private Vector<String> fileName,dirName,numList;
private String files;
private int index;//曲目指针
private int indexForDel;//标志要删除的列表项目的索引
private ButtonGroup buttonGroup;//控制按钮组
private JRadioButtonMenuItem[] buttonValues;
private String[] content={"随机播放","顺序播放","单曲循环"};
MediaPlayer()//构造函数
{
super("java音频播放器");//窗口标题
c=getContentPane();
c.setLayout(new BorderLayout());
fileName=new Vector<String>(1);
dirName=new Vector<String>(1);
numList=new Vector<String>(1);
new Properties(System.getProperties());
listFile=new File("list.text");//播放列表直接存于此目录
Thread readToList=new Thread(this);
list=new JList();
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setFixedCellHeight(25); //播放列表高度
list.setFont(new Font("Serif",Font.PLAIN,15)); //文件名高度
list.setBackground(new Color(0,0,255));
//判断,双击歌曲播放
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2) //双击歌曲播放
{
index = list.locationToIndex(e.getPoint());
createPlayer2();
}
}
public void mouseReleased(MouseEvent e)
{
checkMenu(e);//自定义函数,判断是否是右键,来决定是否显示菜单
}
}
);
scroll=new JScrollPane(list);//用于存放播放列表
readToList.start();
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
bar=new JMenuBar();
setJMenuBar(bar);//此两行创建菜单栏并放到此窗口程序
bar.setBackground(new Color(255,255,100)); //标题栏背景颜色
fileMenu=new JMenu("文件");
bar.add(fileMenu);
choiceMenu=new JMenu("控制");
bar.add(choiceMenu);
//aboutMenu=new JMenu("关于");
//bar.add(aboutMenu);
openItem =new JMenuItem("打开文件");
openDirItem =new JMenuItem("打开目录");
closeItem =new JMenuItem("退出程序");
openItem.addActionListener(this);
openDirItem.addActionListener(this);
closeItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(openDirItem);
fileMenu.add(closeItem);
onTop=new JCheckBoxMenuItem("播放时位于最前面",top);
choiceMenu.add(onTop);
onTop.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(onTop.isSelected())
top=true;
else top=false;
setAlwaysOnTop(top);
}
}
);
choiceMenu.addSeparator();
buttonGroup=new ButtonGroup();
buttonValues=new JRadioButtonMenuItem[3];
for(int bt=0;bt<3;bt++)
{
buttonValues[bt]=new JRadioButtonMenuItem(content[bt]);
buttonGroup.add(buttonValues[bt]);
choiceMenu.add(buttonValues[bt]);
}
buttonValues[0].setSelected(true);
choiceMenu.addSeparator();
//about=new JMenuItem("关于作者");
//about.addActionListener(this);
//aboutMenu.add(about);
//菜单栏设置完毕
panel=new JPanel();
panel.setLayout(new BorderLayout());
c.add(panel,BorderLayout.CENTER);
panelSouth=new JPanel();
panelSouth.setLayout(new BorderLayout());
c.add(panelSouth,BorderLayout.SOUTH);
icon=new ImageIcon("icon\\Player.jpg");
label=new JLabel(icon);
panel.add(label);
//歌曲播放列表添加删除操作
popupMenu=new JPopupMenu();
del =new JMenuItem("删除");//鼠标右键弹出菜单对象实例化
popupMenu.add(del);
del.addActionListener(this);
delAll =new JMenuItem("全部删除");
popupMenu.add(delAll);
delAll.addActionListener(this);
reName =new JMenuItem("重命名");
popupMenu.add(reName);
reName.addActionListener(this);
scroll=new JScrollPane(list);//用于存放播放列表
listB=new JLabel(new ImageIcon("icon\\qingdan.gif"),SwingConstants.CENTER);
panelSouth.add(listB,BorderLayout.NORTH);
panelSouth.add(scroll,BorderLayout.CENTER);
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//设定窗口关闭方式
this.setLocation(400,250);//设定窗口出现的位置
//窗口大小
setSize(350,330);
this.setResizable(false);
this.setVisible(true);//此句不可少,否则窗口会不显示
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==openItem)
{
openFile();
}
if(e.getSource()==openDirItem)
{
openDir();
}
if(e.getSource()==closeItem)
{
exity_n();
}
/*if(e.getSource()==about)
{
JOptionPane.showMessageDialog(this,"JAVA媒体播放器\n"
+"2008科技立项\n "+"数媒0602 顾桂荣 马晓斌 谈一超 蒋泽杰 ","asdasdasdasd" ,JOptionPane.INFORMATION_MESSAGE);
}
*/
if(e.getSource()==del)
{
//index
//delPaintList(index);
fileName.removeElementAt(indexForDel);
dirName.removeElementAt(indexForDel);
numList.removeAllElements();
Enumeration<String> enumFile=fileName.elements();
while(enumFile.hasMoreElements())
{
numList.addElement((numList.size()+1)+"."+enumFile.nextElement());
}
//list.setListData(fileName);
list.setListData(numList);
if(index<indexForDel)
list.setSelectedValue(numList.elementAt(index),true);
else
{
if(index==indexForDel);
else
if(index!=0)
list.setSelectedValue(numList.elementAt(index-1),true);
}
//list.setSelectedIndex(index);
}
if(e.getSource()==delAll)
{
fileName.removeAllElements();
dirName.removeAllElements();
numList.removeAllElements();
list.setListData(numList);
}
if(e.getSource()==reName)
{
String name;//JOptionPane.showInputDialog(this,"请输入新的名字"); 重命名歌曲
try
{
name=reNames();
fileName.setElementAt(name,indexForDel);
numList.setElementAt((indexForDel+1)+"."+name,indexForDel);
}
catch(ReName e2) //该部分代码错误?!
{
}
}
if(e.getSource()==infor)
{
}
}
public static void main(String[] args)
{
final MediaPlayer mp=new MediaPlayer();
mp.setIconImage(new ImageIcon("icon\\mPlayer.jpg").getImage());//改变默认图标
mp.addWindowListener(new WindowAdapter()//注册窗口事件
{
public void windowClosing(WindowEvent e)
{
//System.exit(0);
mp.exity_n();
}
}
);
}
//打开文件
private void openFile()
{
fd = new FileDialog(MediaPlayer.this);
fd.setVisible(true);
if (fd.getFile() != null)
{
title = fd.getDirectory() + fd.getFile();
files=fd.getFile();
file=new File(title);
createPlayer();
}
}
//路径错误抛出
private void openDir()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result=fileChooser.showOpenDialog(MediaPlayer.this);
if(result==JFileChooser.CANCEL_OPTION)
return;
file=fileChooser.getSelectedFile();
if(file==null||file.getName().equals(""))
JOptionPane.showMessageDialog(this,"错误的路径",
"出错了",JOptionPane.ERROR_MESSAGE);
String[] sFiles=file.list();
for(int i=0;i<sFiles.length;i++)
{
fileName.addElement(sFiles[i]);
numList.addElement((numList.size()+1)+"."+sFiles[i]);
dirName.addElement(file.getAbsolutePath()+"\\"+sFiles[i]);
}
list.setListData(numList);
}
@SuppressWarnings("deprecation")
private void createPlayer()
{
closePreviosPlayer();//关闭先前的媒体播放器
String extendName="抱歉,此播放器不支持"+title.substring(title.lastIndexOf(".")+1)+"格式";
try
{
URL url2 = file.toURL();
URL url = url2;
player=Manager.createPlayer(url);//javax.media.Manager直接继承于java.lang.object,且它为final,不能被继承
player.addControllerListener(new ControllerHand());
player.start();
addList(files);
index=fileName.size()-1;
list.setSelectedValue(numList.elementAt(index),true);
setTitle(title);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,extendName,"出错了!!",JOptionPane.ERROR_MESSAGE);
setTitle(extendName);
}
}
private void closePreviosPlayer()
{
if(player==null)
return;
//player.close();//首先停止播放
/*
*不能用上面的代码停止,要用下面的两行取代,否则Component visual =player.getVisualComponent();发生异常
**/
player.stop();
player.deallocate(); //停止播放并且重新装载DateSource
Component visual =player.getVisualComponent();
Component control=player.getControlPanelComponent();
if(visual!=null)
{
panel.remove(visual);
}
if(control!=null)
{
panel.remove(control);
}
}
private class ControllerHand implements ControllerListener
{
public void controllerUpdate(ControllerEvent e)
{
if(e instanceof RealizeCompleteEvent)
{
Component visual=player.getVisualComponent();
if(visual!=null)
{
System.out.println("音频播放器不支持视频图象功能");
setTitle("音频播放器不支持视频图象功能");
}
Component control=player.getControlPanelComponent();
if(control!=null)
{
panel.add(control,BorderLayout.SOUTH);
}
//c.validate();
panel.doLayout();
return;
}
if (e instanceof EndOfMediaEvent)
{
if(buttonValues[0].isSelected())
{
if(fileName.size()==0)
return;
index=(int)(Math.random()*fileName.size());
}
if(buttonValues[1].isSelected())
{
if(fileName.size()==0)
return;//当用户把播放列表清空的时候,返回
index=(index+1)%fileName.size();
}
if(buttonValues[2].isSelected())
{
player.setMediaTime (new Time (0));
player.start();
}
createPlayer2();
}
}
}
private void exity_n()
{
int exi;
exi=JOptionPane.showConfirmDialog(this,"真的要离开么?","退出程序",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
//if(exi==null)
if(exi==JOptionPane.YES_OPTION)
{
saveList();
System.exit(0);
}
return;
}
private void addList(String vf)
{
//fileReadList=new fileReadList(fdd,)
//try
//{
//int i=0;
//fileName.addElement((fileName.size()+1)+"."+vf);
fileName.addElement(vf);
numList.addElement((numList.size()+1)+"."+vf);
//fileName.addElement(++i+"."+vf);
dirName.addElement(title);
list.setListData(numList);
//}
/*catch(Exception e)
{
e.printStackTrace();
//System.out.println(e.getMessage());
}*/
}
@SuppressWarnings("deprecation")
private void createPlayer2()
{
try{title=dirName.elementAt(index).toString();}
//title=dirName.elementAt(index).toString();
catch(ArrayIndexOutOfBoundsException e)
{return;}
file=new File(title);
closePreviosPlayer();//关闭先前的媒体播放器
try
{
URL url = file.toURL();
player=Manager.createPlayer(url);//Java.media.Manager直接继承于java.lang.object,且它为final,不能被继承
player.addControllerListener(new ControllerHand());
player.start();
//list.setSelectedIndex(index);
list.setSelectedValue(numList.elementAt(index),true);
//list.setSelectionForeground(Color.blue);
//list.setSelectedIndex(index);
//addList(files);
setTitle(title);
//addList("files");//到播放清单
}
catch(Exception e)
{
String ex=null;
try{ex=fileName.elementAt(index).toString();
}
catch(Exception e1){return;}
fileName.removeElementAt(index);
numList.removeAllElements();
Enumeration<String> enumFile=fileName.elements();
while(enumFile.hasMoreElements())
{
numList.addElement((numList.size()+1)+"."+enumFile.nextElement());
}
dirName.removeElementAt(index);
list.setListData(numList);
System.out.println("已经从播放列表中删除 "+"\""+ex+"\""+" 文件,"
+"因为此播放器不支持"+ex.substring(ex.lastIndexOf(".")+1)+"格式,");
if(numList.size()!=0)
{
index%=numList.size();
createPlayer2();
}
}
}
private void saveList()
{
try
{
output=new ObjectOutputStream(new FileOutputStream(listFile));
output.flush();
output.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
Thread.sleep(1);
}
catch(InterruptedException e)
{
}
finally
{
if(dirName.isEmpty())//防止Vector越界
{
return;
}
index=(int)(Math.random()*(fileName.size()));//产生随即数,进行随即播放
list.setListData(numList);
//list.setListData(fileName);
//list.setSelectedValue(fileName.elementAt(index),true);
//list.ensureIndexIsVisible(index);//确保选择项可以看见
//list.setSelectionForeground(Color.green);
createPlayer2();
}
}
private void checkMenu(MouseEvent e)
{
if(e.isPopupTrigger())
{
indexForDel=list.locationToIndex(e.getPoint());
int[] selected={index,indexForDel};
//Point p=new Point(e.getX(),e.getY());
list.setSelectedIndices(selected);
popupMenu.show(list,e.getX(),e.getY());
}
//list.setSelectedIndex(index);
}
String reNames() throws ReName//文件该名函数
{
String name=JOptionPane.showInputDialog(this,"请输入新的名字",fileName.elementAt(indexForDel));
if(name==null||name.equals("")) throw new ReName();
return name;
}
class ReName extends Exception//自定义异常来处理文件该名的时候发生输入为空的情形
{
/**
*
*/
private static final long serialVersionUID = 1L;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -