java 不能从静态上下文中引用非静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6185419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
non static variable cannot be referenced from a static context
提问by Karan Dwivedi
I am a Java newbie, so please bear with me and help.
我是 Java 新手,所以请多多包涵和帮助。
I aim to first play then record sound.
我的目标是先播放然后录制声音。
I use netbeans IDE 6.8. Here is the code:
我使用 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
}
Please give specific directions, as I am a noob in Java programming.
请给出具体说明,因为我是 Java 编程的菜鸟。
回答by Lukas Eder
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:
虽然可能有更正式的资源来解释这一点(例如 Java 语言规范),但我经常发现自己查看此网页以了解以下类型的问题:
http://mindprod.com/jgloss/jgloss.html
http://mindprod.com/jgloss/jgloss.html
It explains these things quite well, also for noobs ;-) In your case:
它很好地解释了这些事情,也适用于新手 ;-) 在你的情况下:
回答by Reporter
I used the "Java Editor" and I tried to compiled your class. I got the error masseage
我使用了“Java 编辑器”并尝试编译您的类。我得到了错误按摩
Reg1.java:93:16: non-static method captureAudio() cannot be referenced from a static context
Reg1.java:93:16:不能从静态上下文中引用非静态方法 captureAudio()
The reason is: you call in the method staticvoid main() a method, which need an instance of a object. If a method is not declared as staticyou need follwoing syntax 'referenceObject.captureAudio()'
原因是:您在方法staticvoid main() 中调用了一个方法,该方法需要一个对象的实例。如果方法未声明为静态,则需要以下语法“referenceObject.captureAudio()”
回答by solendil
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();
}
});
}
回答by Nanne
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.)
静态意味着没有对象(类的实例,如new YourClass()
)。如果你有一个静态函数,它应该是“独立的”,所以它不能使用非静态的东西,因为它们使用真实对象中的东西(如成员变量等)
Any static
function can only call and use other static
functions. So look for the trouble in that environment.
任何static
函数只能调用和使用其他static
函数。所以在那个环境中寻找问题。
回答by Boro
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.
在captureAudio()
未声明静态因此是一个实例方法,它不能没有对象在被称为main()
是静态的。
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.
我看到您在运行中创建了 Reg1 的新实例,因此可以调用captureAudio()
此对象的方法。另外,不需要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();
}
});
}