java - Compiler throw non static method cannot accessed from static context 当没有问题

标签 java swing compiler-errors

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Color;
import java.util.Random;

public class dots {
    public dots() {
        init();
    }
    public void init() {
        JFrame frame = new JFrame("Dots");
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        int scrWidth = (int) frame.getSize().getWidth();
        int scrHeight = (int) frame.getSize().getHeight();
        JFrame.getContentPane().add(panel);
        Random rand = new Random();
        Graphics g = panel.getGraphics();
        for (int i = 0; i < 18; i++) {
            g.setColor(i < 12 ? Color.YELLOW : Color.BLUE);
            g.drawOval(Random.nextInt(scrWidth),Random.nextInt(scrHeight),40,40);
        }
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        dots d = new dots();
    }
}

好吧,这没有意义。当我尝试编译它时,我得到了

dots.java:19: non-static method getContentPane() cannot be referenced from a sta
tic context
                JFrame.getContentPane().add(panel);
                      ^
dots.java:24: non-static method nextInt(int) cannot be referenced from a static
context
                        g.drawOval(Random.nextInt(scrWidth),Random.nextInt(scrHe
ight),40,40);
                                         ^
dots.java:24: non-static method nextInt(int) cannot be referenced from a static
context
                        g.drawOval(Random.nextInt(scrWidth),Random.nextInt(scrHe
ight),40,40);
                                                                  ^
3 errors

我显然不是在静态上下文中操作,所以我不知道发生了什么。真诚感谢任何帮助!

最佳答案

这些是实例方法,因此您需要在对象而不是类上调用它们。

frame.getContentPane().add(panel);
// ...
g.drawOval(rand.nextInt(scrWidth), rand.nextInt(scrHeight),40,40);

关于java - Compiler throw non static method cannot accessed from static context 当没有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3643952/

相关文章:

java - 如何在不同的线程中使用 JProgressBar?

java - 无法获得要编译的代码,有什么想法吗?

caching - 如何处理并发Web用户的重置CS-Script

java - 将箭头键监听器添加到实现 ActionListener 的 Jframe

compiler-errors - gfortran包含带有子例程的目录

java - 更新到 Android Studio 3.2 后,Gradle 构建卡住并且永远不会完成

java - 向服务器发送 GPS 数据不起作用?

java - netty维护连接以及如何通知失败到channelfuture

java - Amazon Alexa Web 服务总是给出 401

java - 当状态改变时阻止 JComponent 重新绘制