【问题标题】:Why does my Oval not print to the JFrame? [duplicate]为什么我的 Oval 不打印到 JFrame? [复制]
【发布时间】:2016-05-25 20:15:45
【问题描述】:

每当我运行它时,我都会收到错误:

“anime.re.drawShape(re.java:17) atanime.re.main(re.java:12) 的线程“main”java.lang.NullPointerException 中的异常”

我没有传递空引用,有什么问题?

import javax.swing.JFrame;
import java.awt.Graphics;

public class re {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        Graphics g = frame.getGraphics();
        drawShape(g);
        frame.setVisible(true);
    }

    public static void drawShape(Graphics g) {
        g.drawOval(0, 0, 100, 100);

    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    使用 Graphics2D 的绘制方法,而不是创建自己的方法。您的空指针异常也来自于在设置 jpanel 或使 jframe 可见之前尝试绘制。

    public class example extends JPanel{
    
    public static void main(String[] args){
        JFrame frame = new JFrame("Example");
        example main = new example();
        int miliSecs = 25;
    
        frame.add(main);
    
        frame.setSize(640, 480);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    
        frame.repaint();//here is the call to the paint method
    }
        public void paint ( Graphics g ){
        //paints the screen
        g.setColor(Color.BLACK);
        g.fillRect(0,0,640,480);
        }
    }
    

    这样,您还可以调用update() 方法和paint() 方法一起清除每一帧的屏幕。

    【讨论】:

      猜你喜欢
      • 2017-03-21
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2020-06-05
      相关资源
      最近更新 更多