我有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 :(得分: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);
}
}