开发者

non static variable cannot be referenced from a static context

I am a Java newbie, so please bear with me and help.

I aim to first play then record sound.

I use netbeans IDE 6.8. Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;


public class Reg1 extends javax.swing.JFrame {
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
        public Reg1() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Stop");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton1MouseReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(211, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(237, 237, 237))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(287, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(65, 65, 65))
        );

        pack();
    }// </editor-fold>

    private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {

        targetDataLine.stop();
        targetDataLine.close();

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Reg1();
            }
            private void Reg1(){

                KeyListener s;

                try {
            AudioInputStream audio = AudioSystem.getAudioInputStream(new File("name.wav"));
            Clip clip = AudioSystem.getClip();
            clip.open(audio);
            clip.start();
        }

        catch(UnsupportedAudioFileException uae) {
            System.out.println(uae);
        }
        catch(IOException ioe) {
            System.out.println(ioe);
        }
        catch(LineUnavailableException lua) {
            System.out.println(lua);
        }
               captureAudio();

            }
        });
    }
  private void captureAudio(){
    try{

   开发者_如何学编程   audioFormat = getAudioFormat();
      DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class,audioFormat);
      targetDataLine = (TargetDataLine)
               AudioSystem.getLine(dataLineInfo);


      new CaptureThread().start();
    }catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }


  public static AudioFormat getAudioFormat(){

    float sampleRate = 8000.0F;    
    int sampleSizeInBits = 16;    
    int channels = 1;    
    boolean signed = true;    
    boolean bigEndian = false;   
    return new AudioFormat(sampleRate,
                           sampleSizeInBits,
                           channels,
                           signed,
                           bigEndian);
  }

class CaptureThread extends Thread{

  public void run(){
    AudioFileFormat.Type fileType = null;
    File audioFile = null;
    fileType = AudioFileFormat.Type.WAVE;
    audioFile = new File("name.wav");
    try{
      targetDataLine.open(audioFormat);
      targetDataLine.start();
      AudioSystem.write(
            new AudioInputStream(targetDataLine),
            fileType,
            audioFile);
    }catch (Exception e){
      e.printStackTrace();
    }

  }
}


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}

Please give specific directions, as I am a noob in Java programming.


While there may be more formal resources to explain this (e.g. the Java Language Specification), I frequently find myself checking this webpage for these kinds of questions:

http://mindprod.com/jgloss/jgloss.html

It explains these things quite well, also for noobs ;-) In your case:

  • http://mindprod.com/jgloss/static.html also linking to:
  • http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html


I used the "Java Editor" and I tried to compiled your class. I got the error masseage

Reg1.java:93:16: non-static method captureAudio() cannot be referenced from a static context

The reason is: you call in the method static void main() a method, which need an instance of a object. If a method is not declared as static you need follwoing syntax 'referenceObject.captureAudio()'


Static means that there is no object (instance of class, like new YourClass()). If you have a static function, it is supposed to be "standalone", so it cannot use non-static things, because they use stuff in a real object (like member variables etc.)

Any static function can only call and use other static functions. So look for the trouble in that environment.


Replace your main with :

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            Reg1 r = new Reg1();
            try {
                AudioInputStream audio = AudioSystem.getAudioInputStream(new File("name.wav"));
                Clip clip = AudioSystem.getClip();
                clip.open(audio);
                clip.start();
            }
            catch (Exception e) {
                System.out.println(e);
            }
            r.captureAudio();
        }
    });
}


The captureAudio() is not declared static thus it is an instance method and it cannot be called without an object in main() which is static.

Sine I see you have createed in the run methid new instance of Reg1 thus it is fine then to call the method captureAudio() for this object. Plus there is no need for the inner private void Reg1() method which BTW you were never calling. I propose that you change main to something like this.

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                Reg1 reg1 = new Reg1();
                KeyListener s;    
                try
                {
                    AudioInputStream audio = AudioSystem.getAudioInputStream(new File("name.wav"));
                    Clip clip = AudioSystem.getClip();
                    clip.open(audio);
                    clip.start();
                }catch(UnsupportedAudioFileException uae)
                {
                    System.out.println(uae);
                }catch(IOException ioe)
                {
                    System.out.println(ioe);
                }catch(LineUnavailableException lua)
                {
                    System.out.println(lua);
                }
                reg1.captureAudio();
            }
        });
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜