Java JPanel中getGraphics()中的空指针

Java JPanel中getGraphics()中的空指针,java,jpanel,Java,Jpanel,嘿,当我试图在paintComponent中使用图形对象时,我会遇到一个NullPointerException,我不知道为什么。它仍然绘制了一次我想要的内容,但在那之后,它抛出了异常。这是密码 public class RacePanel extends JPanel implements MouseListener, ActionListener { private static final int PANEL_WIDTH = 640; private static final int P

嘿,当我试图在paintComponent中使用图形对象时,我会遇到一个NullPointerException,我不知道为什么。它仍然绘制了一次我想要的内容,但在那之后,它抛出了异常。这是密码

public class RacePanel extends JPanel implements MouseListener, ActionListener
{

private static final int PANEL_WIDTH = 640;
private static final int PANEL_HEIGHT = 400;
private Timer time;
boolean firstTime;
private Rabbit hare;

public RacePanel()
{
    setSize(PANEL_WIDTH, PANEL_HEIGHT);
    setVisible(true);
    firstTime = true;
    addKeyListener(new Key());
    addMouseListener(this);
    hare = new Rabbit();
    time = new Timer(40, this);
    time.start();
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    setBackground(Color.WHITE);

    g.setColor(Color.RED);
    g.drawLine(0, this.getHeight(), this.getWidth()/4, this.getHeight()/2);
    g.drawLine(this.getWidth()/4, this.getHeight()/2, 2*this.getWidth()/4, this.getHeight());
    g.drawLine(2*this.getWidth()/4, this.getHeight(), 3*this.getWidth()/4, this.getHeight()/2);
    g.drawLine(3*this.getWidth()/4, this.getHeight()/2, this.getWidth(), this.getHeight());
    g.setColor(Color.PINK);
    g.fillOval(hare.getPosition(), this.getHeight()-10, 10, 10);


}
@Override
public void actionPerformed(ActionEvent arg0)
{
    Graphics g = getGraphics();
    paintComponent(g);
    hare.move();

}
public static void main(String[] args) 
{
    RacePanel panel = new RacePanel();
    panel.setVisible(true);
    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.setMinimumSize(panel.getSize());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.addKeyListener(panel.new Key());
    frame.pack();
    frame.setVisible(true);
}
}
一旦到达g=getGraphics()时,g为null,对super.paintComponent(g)的调用将抛出异常。我从我以前的一个项目中复制了很多动画代码,在那里一切都很好,所以我很困惑为什么这不起作用。

@Override
public void actionPerformed(ActionEvent arg0)
{
    Graphics g = getGraphics();
    paintComponent(g);
    hare.move();

}
这不是Swing中定制绘画的工作方式。没有任何理由可以直接调用
paintComponent
(甚至
paint
),它们由绘制子系统调用

首先,查看和了解有关绘制系统如何工作的更多详细信息

如果希望更新UI,则应调用
repaint
,这将在未来一段时间内安排绘制过程

您可能还想看一看,这将有助于解决与
KeyListener

如果你喜欢绘画过程中的“完全”控制,你可以考虑看一看,虽然这是一个完全转变的想法