无法从静态上下文引用非静态变量

时间:2011-05-31 09:17:03

标签: java

我是Java新手,所以请耐心帮助。

我的目标是先播放然后录制声音。

我使用netbeans IDE 6.8。这是代码:

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

}

请给出具体指示,因为我是Java编程中的菜鸟。

5 个答案:

答案 0 :(得分:3)

虽然可能有更多正式资源来解释这一点(例如Java语言规范),但我经常发现自己在这个网页上查看这些类型的问题:

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

它很好地解释了这些事情,也适用于新手;-) 在你的情况下:

答案 1 :(得分:3)

我使用了“Java编辑器”,我试图编译你的类。我得到了错误masseage

  

Reg1.java:93:16:非静态方法captureAudio()无法从静态上下文中引用

原因是:你在方法中调用 static void main()一个方法,它需要一个对象的实例。如果方法未声明为 static ,则需要使用以下语法'referenceObject.captureAudio()'

答案 2 :(得分:2)

静态意味着没有对象(类的实例,如new YourClass())。如果你有一个静态函数,它应该是“独立的”,所以它不能使用非静态的东西,因为它们在真实对象中使用东西(比如成员变量等)。

任何static函数只能调用和使用其他static函数。所以在那种环境中寻找麻烦。

答案 3 :(得分:2)

用以下内容替换你的主页:

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

答案 4 :(得分:0)

captureAudio()未声明为静态,因此它是一个实例方法,如果main()中的对象是静态的,则无法调用它。

我发现你已经在运行的methid新实例中创建了Reg1,因此可以为该对象调用方法captureAudio()。此外,您不需要使用BTW的内部private void Reg1()方法。我建议你把main改成这样的东西。

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