1

I am having problem with this code:

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); } } } 

It is saying that

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

If I make the InputStream variable static then its telling me illegal start of expression. I have also removed the this keyword. Still the problem is not solving. How can fix it?

1
  • 1
    What would this be without an instance? Commented Nov 27, 2012 at 21:39

3 Answers 3

4

Just avoid the problem, like so:

JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav"); 
Sign up to request clarification or add additional context in comments.

3 Comments

owao! ! ! the error has gone. Now I can understand it. But when I run the program its giving me another exception error: java.lang.NullPointerException why?
@Tushar I recommend you accept one of these answers to finish this question. Then submit the new problem as a new question.
@Tushar: probably it can't find the wav file. getResourceAsStream returns null if the file isn't present. also: 1) I agree with Guido's comment, 2) asking people to explain an exception without showing them a stacktrace is unreasonable.
1

To accomplish this, use a class literal instead:

 is = JavaApplication16.class.getClassLoader().getResourceAsStream("samp.wav"); 

Comments

1

you cant use this keyword inside a static method. this keyword can only be used Within an instance method or a constructor. this is a reference to the current object.

try:

 is = YourClassName.class.getClassLoader().getResourceAsStream("samp.wav"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.