JPanel中的getGraphics()中的NullPointer

时间:2018-05-01 23:02:41

标签: java jpanel

嘿,当我尝试在paintComponent中使用Graphics对象时,我得到一个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)的调用抛出异常。我从之前的一个项目中复制了很多动画代码,一切都运行良好,所以我很困惑为什么这不起作用。

1 个答案:

答案 0 :(得分:0)

此...

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

}

不是Swing中自定义绘画的工作原理。从来没有任何理由直接调用paintComponent(或甚至paint),它们由绘画子系统调用。

首先查看Performing Custom PaintingPainting in AWT and Swing,了解有关绘画系统如何运作的详细信息

如果您想要更新UI,您应该调用repaint,这将在未来一段时间内安排绘画通行证

您可能还想查看How to Use Key Bindings,这有助于解决与KeyListener

相关的可靠性问题

如果你喜欢"完成"控制绘画过程,您可能会考虑查看BufferStrategy and BufferCapabilities,但这是思维的完全转变