我正在尝试使用 Swing Timer 在 Java 中为椭圆设置动画。我相信下面的代码应该可以完成这项工作,但是当我运行我的程序时,计时器会抛出一个NullPointerException
. 知道为什么会这样吗?
我已经排除了带有主线的代码,因为它不相关。这是我的错误,它发生在actionlistener
'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);
}
}
定时器类:
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();
}
}
}
形状类(试图为这个对象设置动画):
public class Ellipse extends java.awt.geom.Ellipse2D.Double {
private Glitchpanel glitch;
private double x, y, w, h;
public Ellipse() {
super();
double x = 100;
double y = 100;
double w = 100;
double h = 100;
this.setFrame(x, y, w, h);
}
public void setX(double x2) {
x = x2;
}
public void setY(double y2) {
y = y2;
}
}