日期:2014-05-20 浏览次数:20732 次
package com.test1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
public class JSoundDemo extends JFrame implements ActionListener{
public static void main(String[] args) {
// TODO Auto-generated method stub
JSoundDemo jsd=new JSoundDemo();
}
JPanel contentPanel;
JTextField jtf=new JTextField();
JPanel jPanel1=new JPanel();
JLabel jLabel1=new JLabel();
JButton jButton1=new JButton();
JButton jButton2=new JButton();
java.applet.AudioClip clip=null;
java.lang.ClassLoader cl=null;
public JSoundDemo(){
super();
this.setVisible(true);
this.setBounds(500, 250, 418,118);
this.setTitle("JSoundDemo");
jLabel1.setFont(new Font("Dialog",Font.BOLD,18));
jLabel1.setToolTipText("");
jLabel1.setText("waiting.....");
jButton1.setText("PLAY");
jButton1.addActionListener(this);
jButton2.setText("STOP");
jButton2.setEnabled(false);
jButton2.addActionListener(this);
jtf.setText(ClassLoader.getSystemResource("Sounds/12.au").toString());
//为什么这句显示空指针异常
contentPanel=(JPanel) this.getContentPane();
contentPanel.add(jtf,BorderLayout.NORTH);
jPanel1.add(jButton1);
jPanel1.add(jButton2);
contentPanel.add(jPanel1,BorderLayout.CENTER);
contentPanel.add(jLabel1,BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==jButton1){
System.out.println("hahh");
jButton1.setEnabled(false);
jButton2.setEnabled(true);
//实例化clip
try {
clip=java.applet.Applet.newAudioClip(new java.net.URL(jtf.getText()));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
clip.play();
jLabel1.setText("NowPlaying"+jtf.getText());
}
if(e.getSource()==jButton2){
System.out.println("woa");
jButton1.setEnabled(true);
jButton2.setEnabled(false);
clip.stop();
jLabel1.setText("waiting");
}
}
}
URL url= ClassLoader.getSystemResource("Sounds/12.au");我把你的代码分解了下,发现url是空的,由于对swing不是很了解,也不知道该怎么给你解释;估计是路径的问题,你可以把12.au放到src目录下,不要sounds目录试试;
System.out.println(url);
String text=url.toString();
jtf.setText(text);