在Java Swing库中使用图形与面板的问题

时间:2008-11-11 01:42:23

标签: java swing graphics nullpointerexception panels

大家好,我正在尝试运行以下程序,但是我得到了一个N​​ullPointerException。我是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行。

提前致谢,

托梅克

2 个答案:

答案 0 :(得分:4)

您正在获取NPE,因为g未设置,因此,它是null。此外,您不应该在构造函数中进行绘制。而是重载paintComponent(Graphics g)

public class Gallow extends JPanel {
    public paintComponent(Graphics g){
        g.fillOval(10, 20, 40, 25);       
    }
}

我也会研究BufferedImage

答案 1 :(得分:0)

以下几点:不要忘记将面板添加到JFrame。并为您的自定义绘画覆盖paint() JPanel方法。您不需要声明Graphics对象,因为JPanel的paint方法在任何情况下都会引用一个。

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);
        add(gallow, BorderLayout.CENTER);//here
        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 {

    public Gallow(){
        super();
    }

    public void paint(Graphics g){
        g.fillOval(10, 20, 40, 25);       
    }
}