gpt4 book ai didi

java - 为什么我的 Oval 无法打印到 JFrame?

转载 作者:行者123 更新时间:2023-12-01 10:24:48 24 4
gpt4 key购买 nike

每当我运行此命令时,我都会收到错误:

"Exception in thread "main" java.lang.NullPointerException at anime.re.drawShape(re.java:17) at anime.re.main(re.java:12)"

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

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

}
}

最佳答案

使用Graphics2D的paint方法而不是创建自己的方法。另外,您的空指针异常是由于在设置 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() 方法一起清除每一帧的屏幕。

关于java - 为什么我的 Oval 无法打印到 JFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com