各位大大好,我是跟着视频自学的java纯新手,在写的代码中出现了一些问题想请教一下 代码如下
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
public class myFrame extends JFrame implements KeyListener{
private ListallBG=new ArrayList();
private background nowBG=null;
public static void main(String args[]){
new myFrame();
}
public myFrame(){
this.setTitle("马里奥游戏程序");
this.setSize(900,600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
//初始化场景之前要初始化全部图片
StaticValue.init();
//创建全部场景
for(int i=1;i<=3;i++){
this.allBG.add(new background(i,i==3?true:false));
}
//将第一个场景设置为当前场景
this.nowBG=this.allBG.get(0);
//测试nowBG是否为空,非空
if(nowBG==null){
System.out.println("is null");
}
else
System.out.println("not null");
this.repaint();
this.addKeyListener(this);
}
public void paint (Graphics g){
//建立临时缓冲图片
BufferedImage image=new BufferedImage(900,600,BufferedImage.TYPE_3BYTE_BGR);
Graphics g2=image.getGraphics();
if (nowBG!=null){
g2.drawImage(this.nowBG.getBgImage(),0,0,this);
System.out.println("is not null");
}
else
System.out.println("is null");
//把图片绘制到窗体
g.drawImage(image,0,0,this);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
char a=e.getKeyChar();
int b=e.getKeyCode();
System.out.println(a+" "+b);
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
显示出来的结果是
is null
not null
is not null
我想问一下paint()在什么时候被调用的?为什么被调用了两次?为什么paint()第一次被调用的时候nowBG没有被初始化。然后就是运行的时候如果去掉paint()里的if else判断直接调用g2.drawImage(this.nowBG.getBgImage(),0,0,this)会出现java.lang.NullPointerException这该如何解决