publicclassMusicDemo2extendsJFrameimplementsActionListener{privatestaticintWIDTH=800,HEIGHT=600;JButtonb_play,b_stop,b_loop,b_exit;JPanelp;URLurl=null;AudioClipac;publicM...
public class MusicDemo2 extends JFrame implements ActionListener{
private static int WIDTH = 800, HEIGHT = 600;
JButton b_play, b_stop, b_loop,b_exit;
JPanel p;
URL url=null;
AudioClip ac;
public MusicDemo2() {
try {
url=new File("D:\\music\\1.wav").toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AudioClip ac = java.applet.Applet.newAudioClip(url);
b_play = new JButton("播放");
b_play.addActionListener(this);
b_play.setActionCommand("play");
b_stop = new JButton("停止");
b_stop.addActionListener(this);
b_loop = new JButton("循环");
b_loop.addActionListener(this);
b_exit=new JButton("退出");
b_exit.addActionListener(this);
b_exit.setActionCommand("exit");
p = new JPanel();
((JPanel) this.getContentPane()).setOpaque(false);
ImageIcon img = new ImageIcon("D:\\picture\\1.jpg");
JLabel background=new JLabel(img);
background.setBounds(0, 0, img.getIconWidth(),img.getIconHeight());
this.getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));// 注意这里是关键,将背景标签添加到jfram的LayeredPane面板里。
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.setLayout(new FlowLayout());
p.add(b_play);
p.add(b_stop);
p.add(b_loop);
p.add(b_exit);
add(p, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MusicDemo2 md = new MusicDemo2();
md.setBounds(200, 3, WIDTH, HEIGHT);
}
public void actionPerformed(ActionEvent e) {
String s=e.getActionCommand();
if(s.equals("play")){
if(ac!=null){
ac.play();
}
}else if(s.equals("stop")){
if(ac!=null){
ac.stop();
}
}else if(s.equals("loop")){
if(ac!=null){
ac.loop();
}
}else if(s.equals("exit")){
System.exit(0);
}
}
}
展开