在 Java Swing 库中使用带有面板的图形的问题
大家好,我正在尝试运行以下程序,但收到 NullPointerException。 我是 Java swing 库的新手,所以我可能会做一些非常愚蠢的事情。 不管怎样,这是我的两个课程,我现在只是在玩,我想做的就是画一个该死的圆圈(我想画一个绞刑架,最后上面有一个刽子手)。
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Hangman2 extends JFrame{
private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
private Gallow gallow = new Gallow();
public Hangman2() {
setLayout(alphabetLayout);
setSize(1000,500);
setVisible( true );
}
public static void main( String args[] ) {
Hangman2 application = new Hangman2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Gallow extends JPanel {
private Graphics g;
public Gallow(){
g.fillOval(10, 20, 40, 25);
}
}
NullPointerException 出现在 g.fillOval 行。
预先感谢,
托梅克
Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Hangman2 extends JFrame{
private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
private Gallow gallow = new Gallow();
public Hangman2() {
setLayout(alphabetLayout);
setSize(1000,500);
setVisible( true );
}
public static void main( String args[] ) {
Hangman2 application = new Hangman2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Gallow extends JPanel {
private Graphics g;
public Gallow(){
g.fillOval(10, 20, 40, 25);
}
}
The NullPointerException comes in at the g.fillOval line.
Thanks in advance,
Tomek
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您收到 NPE 是因为未设置
g
,因此它是null
。 此外,您不应该在构造函数中进行绘图。 重载 改为paintComponent(Graphics g)
。我还会研究 BufferedImage< /a>.
You're getting NPE because
g
is not set, therefore, it'snull
. Furthermore, you shouldn't be doing the drawing in the constructor. OverloadpaintComponent(Graphics g)
instead.I'd also look into BufferedImage.
有几点:不要忘记将面板添加到
JFrame
中。 并重写JPanel
的paint()
方法来进行自定义绘画。 您不需要声明 Graphics 对象,因为在任何情况下JPanel
的 Paint 方法都会引用该对象。A couple of things: Don't forget to add the panel to the
JFrame
. And override thepaint()
method ofJPanel
for your custom painting. You do not need to declare a Graphics object since theJPanel
's paint method will have a reference to one in any case.