我正在尝试使用Swing Timer在Java中为椭圆设置动画。我相信以下代码应该可以完成这项工作,但是当我运行程序时,计时器会抛出NullPointerException
。知道为什么会这样吗?
我已使用主线排除了代码,因为它不相关。这是我的错误,它出现在actionlistener
的{{1}}方法的第一行:
actionperformed
小组类:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Timer$MoveListener.actionPerformed(Timer.java:18)
计时器类:
import java.awt.geom.*;
public class Glitchpanel extends javax.swing.JPanel {
private Ellipse ellipse;
private java.awt.Dimension size;
private Timer timer;
public Glitchpanel() {
super();
ellipse = new Ellipse();
size = new java.awt.Dimension(1000, 1000);
timer = new Timer(ellipse, this);
timer.start();
this.setSize(size);
this.setPreferredSize(size);
this.setBackground(java.awt.Color.WHITE);
}
public void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
java.awt.Graphics2D brush = (java.awt.Graphics2D) g;
brush.draw(ellipse);
}
}
Shape Class(试图为此对象设置动画):
import java.awt.geom.*;
public class Timer extends javax.swing.Timer {
private Glitchpanel glitch;
private Ellipse ellipse;
public Timer(Ellipse ellipse, Glitchpanel glitch) {
super(100, null);
ellipse = ellipse;
glitch = glitch;
this.addActionListener(new MoveListener());
}
private class MoveListener implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
ellipse.setX(ellipse.getX()+1);
ellipse.setY(ellipse.getY()+1);
glitch.repaint();
}
}
}
答案 0 :(得分:3)
变化:
public Timer(Ellipse ellipse, Glitchpanel glitch) {
super(100, null);
ellipse = ellipse;
glitch = glitch;
this.addActionListener(new MoveListener());
}
为:
public Timer(Ellipse ellipse, Glitchpanel glitch) {
super(100, null);
this.ellipse = ellipse;
this.glitch = glitch;
this.addActionListener(new MoveListener());
}