2013-08-05 97 views
2

我想使用Swing Timer在Java中爲橢圓動畫。我相信下面的代碼應該完成這項工作,但是當我運行我的程序時,計時器會拋出一個NullPointerException。任何想法,爲什麼這可能是?爲什麼這個Swing Timer代碼拋出一個NullPointerException?

我已經排除了主線的代碼,因爲它是不相關的。這是我的錯誤,這是occurrs在actionlisteneractionperformed方法的第一行:

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; 
    } 
} 

回答

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()); 
} 
+0

我做了上述無濟於事 - 仍然得到同樣的空指針。雖然謝謝! – user2654199

+0

@ user2654199真的是一樣的嗎?錯誤在於'ellipse'爲空。你可以通過不設置'毛刺'幾乎相同的錯誤(我固定在上面的代碼) – kiheru

+0

我說得太快了,這實際上是固定的。我感謝您的幫助! – user2654199

相關問題