java - "non-static variable this cannot be referenced from a static context"错误

标签 java compiler-errors non-static

这个问题在这里已经有了答案:





Non-static variable cannot be referenced from a static context

(15 个回答)



"Non-static method cannot be referenced from a static context" error

(4 个回答)


5年前关闭。




感谢您花时间帮助我。

我对“非静态...”错误有疑问,我不知道为什么。这是代码

public class Klient {
    public static String output = "test";
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 9898);
        PrintStream PS = new PrintStream(socket.getOutputStream());

        InputStreamReader IR = new InputStreamReader(socket.getInputStream());
        BufferedReader BR = new BufferedReader(IR);

        int i;
        for (i = 0; i < 3; i++) {
            output = BR.readLine();
            Server2.setTekst(output);
        }

(这只是代码的一部分。我知道这在解释时结束)

而另一类:
public class Server2 extends JFrame implements Runnable {
    konsol = new JTextPane();
    konsol.setEditable(false);

    public void setTekst(String tekst) {
        konsol.setText(tekst);
    }

    public void run() {
        instance = new Server2();
        instance.setVisible(true);
    }
}

同样,这也只是代码的一部分。我将衷心感谢您的帮助 :)

最佳答案

将此方法设为静态

public static void setTekst(String tekst){
    konsol.setText(tekst);
}

关于java - "non-static variable this cannot be referenced from a static context"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854468/

相关文章:

java - CheckingButton 后台资源 Id android

java - 过滤未知类型对象的最干净模式?

java - 在java中创建多个不同的标识符

java - 非静态初始化器奇怪的行为

java - Hibernate:如何创建保存的过滤器然后使用它们?

java - 我如何使用java库?

java - Java代码中用来防止其被复制,粘贴和编译的不可识别字符列表

ios - Xcode:构建失败:错误消息

C++:为什么我不能使用 Opencv 访问 Node 类?

java - 不能从静态上下文中引用非静态变量