java - JPanel 中 getGraphics() 中的 NullPointer
问题描述
嘿,当我尝试在 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) 的调用将引发异常。我从我以前的一个项目中复制了很多动画代码,并且在那里一切正常,所以我很困惑为什么这不起作用。
解决方案
这个...
@Override
public void actionPerformed(ActionEvent arg0)
{
Graphics g = getGraphics();
paintComponent(g);
hare.move();
}
不是 Swing 中的自定义绘画的工作方式。没有任何理由应该直接调用paintComponent
(或什至paint
),它们是由绘画子系统调用的。
首先查看在 AWT 和 Swing中执行自定义绘画和绘画,了解有关绘画系统如何工作的更多详细信息
如果您希望更新 UI,您应该调用repaint
,这将在未来一段时间内安排一次绘制通道
您可能还想看看How to Use Key Bindings,这将有助于解决与KeyListener
如果您更喜欢对绘画过程进行“完全”控制,您可以考虑查看BufferStrategy 和 BufferCapabilities,不过,这是一个彻底的思维转变
推荐阅读
- node.js - Slack node js程序运行会话关闭
- python - 使用 json_normalize 对带有嵌套数组的 json 进行规范化
- python - 如何在异步事件循环中使用 multiprocessing.Event?
- node.js - 在 node.js 中使用本机 Windows 函数 GetNamedSecurityInfoA
- javascript - 有没有更好的方法来重定向网站上所有打开的会话?
- mysql - MySQL 的 float(24) 列所需的存储大小是多少?
- python - 从python中的API替换单词
- java - x如何使用 Spring Data JPA 在 Spring 中为 CrudRepository 提供 @Id 字符串?
- javascript - HTML按下时更改文本不起作用
- asp.net-core - ConnectedService.json 环境覆盖