Java 类之间的对象交互

Java 类之间的对象交互,java,object,Java,Object,我有三节课。运行它之后,它会给我java.lang.NullPointerException 我认为我的mf对象之间的交互有问题。 我包括了一些问题代码,请看一下 public class PanelOne extends JPanel{ /*other code*/ private myFrame mf; public Timer timer = new Timer(delay, new TimerHandler()); public PanelOne(){

我有三节课。运行它之后,它会给我
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*/
}



你做错了什么。因此,将参数放入新的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);
}
}

堆栈跟踪说明了什么是导致
NullPointerException
?线程“AWT-EventQueue-0”java.lang.NullPointerException中的异常。声明了
PanelOne.timer
的位置?是的,它在PanelOne类中-public timer timer timer=new timer(delay,new timer handler());当您遇到异常时,可以放置try/catch块并使用System.out.println();在代码中找到错误的位置。关于这个问题,我的问题太多了吗
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);
    }
}
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);
}
}