1

我对这段代码有疑问:

package javaapplication16;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class JavaApplication16 {
    public static void main(String[] args) {
        NewJFrame n = new NewJFrame();
        n.setVisible(true);
        InputStream is;
        is = this.getClass().getClassLoader().getResourceAsStream("samp.wav");
        try {
            AudioStream audioStream;
            audioStream = new AudioStream(is);
            AudioPlayer.player.start(audioStream);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}

它是说

error: non-static variable this cannot be referenced from a static context
        is = this.getClass().getClassLoader().getResourceAsStream("samp.wav");

如果我将 InputStream 变量设为静态,那么它会告诉我表达式的非法开始。我也删除了this关键字。问题仍然没有解决。如何解决?

4

3 回答 3

4

Just avoid the problem, like so:

JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav");
于 2012-11-27T21:40:46.313 回答
1

你不能this keyword在静态方法中使用。this关键字只能在实例方法或构造函数中使用。this是对当前对象的引用。

尝试:

    is = YourClassName.class.getClassLoader().getResourceAsStream("samp.wav");
于 2012-11-27T21:39:38.663 回答
1

为此,请改用类文字:

    is = JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav");
于 2012-11-27T21:42:23.157 回答