2014-09-25 86 views
-1

我有3个类。运行后,它给我java.lang.NullPointerException
我相信我的mf对象之间的交互有问题。
我包括我的问题代码一些地方,请大家看看类之间的对象交互

public class PanelOne extends JPanel{ 
    /*other code*/ 

    private myFrame mf; 
public Timer timer = new Timer(delay, new TimerHandler()); 

    public PanelOne(){ 
     super(); 
     timer.start(); 
     //setBackground(Color.CYAN); 
    } 
    public PanelOne (myFrame mf){ 
     super(); 
     this.mf = mf; 
    } 

    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     mf.P2.spot.setBounds(getWidth(), getHeight()); 
     mf.P2.spot.move(); 
     mf.P2.spot.draw(g);//if change is true the ball is not red 
    } 

    /*other code*/ 
} 

public class PanelTwo extends JPanel{ 
    /*other code*/ 

    private myFrame mf; 
public Spot spot = new Spot(100,100,20); 
    public PanelTwo(){ 
     super(); 
     /*other code*/ 
    } 

    public PanelTwo(myFrame mf){ 
     super(); 
     this.mf = mf; 
    } 

    public class ButtonHandler implements ActionListener { 
     public void actionPerformed(ActionEvent ac){ 
      if(ac.getSource()==quit){ 
       System.exit(0); 
      } 
      if(ac.getSource()==stop){ 
       mf.P1.timer.stop();  
      } 
      if(ac.getSource()==start){ 
       mf.P1.timer.start(); 
      }  
     } 
    } 
} 

public class myFrame extends JFrame{ 
    public PanelOne P1 = new PanelOne(); 
    public PanelTwo P2 = new PanelTwo(); 

    public myFrame(){ 
     super("MyFrame"); 
     /*other code*/ 
    } 

    public static void main(String args[]){ 
     myFrame mf = new myFrame(); 
     mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

堆栈跟踪说的是'NullPointerException'的原因是什么? – dimo414 2014-09-25 04:04:46

+0

线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException – Manbran 2014-09-25 04:06:44

+0

[* stack trace *](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how - 可以 - 我使用的,其调试的,我的,应用程序的错误)。 – dimo414 2014-09-25 04:07:37

回答

0

你做了错误。因此,将参数放在一个新的PanelOne()和新的PanelTwo()对象中,如下所示。

public class myFrame extends JFrame{ 
    public PanelOne P1 = new PanelOne(this); 
    public PanelTwo P2 = new PanelTwo(this); 
public myFrame(){ 
    super("MyFrame"); 
    .......... 
} 
public static void main(String args[]){ 
    myFrame mf = new myFrame(); 
    mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 
} 
+0

当你面对异常时,你可以放置try/catch块并使用System.out.println();在你的代码中找到错误的地方。 – 2014-09-25 04:24:18

+0

[这里](http://stackoverflow.com/questions/26025061/stop-start-bouncing-ball-on-a-frame-java?noredirect=1#comment40765296_26025061)也是我的问题,关于这个问题 – Manbran 2014-09-25 04:43:13