程序如下:
package example;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BackFrame {
JFrame frm;
JPanel pnl;
Backimage bi;
public void frm(){
frm=new JFrame("背景图片");
pnl=new JPanel();
bi=new Backimage();
bi.setImage(new ImageIcon("bg.jpg").getImage());
pnl.add(bi);
frm.add(pnl);
frm.setLocation(500, 100);
frm.setSize(600, 450);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
BackFrame bf=new BackFrame();
bf.frm();
}
}
package example;
import java.awt.Graphics;
import java.awt.Image;
public class Backimage extends javax.swing.JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
Image image=null;
Graphics g=this.getGraphics();
public void setImage(Image image){
this.image=image;
this.paintComponent(g);
}
public void paintComponent(Graphics g){
if(image!=null){
boolean b=g.drawImage(image, 0,0,this);
System.out.println(b);
}
super.paintComponent(g);
}
}
报的是错误是:
Exception in thread "main" java.lang.NullPointerException
at example.Backimage.paintComponent(Backimage.java:17)
at example.Backimage.setImage(Backimage.java:13)
at example.BackFrame.frm(BackFrame.java:13)
at example.BackFrame.main(BackFrame.java:23)
但是我不知道哪里空指针了???
如果你有好的实现背景图片的程序可以分享一下!!!!
------解决方案--------------------
应该是图片的路径问题。在 System.getProperty("user.dir") 这个路径下找不到图片。
另外这个类修改一下:
- Java code
package example;import java.awt.Graphics;import java.awt.Image;public class Backimage extends javax.swing.JPanel{ private static final long serialVersionUID = 1L; Image image=null; public void setImage(Image image){ this.image=image; repaint(); } public void paintComponent(Graphics g){ if(image!=null){ boolean b=g.drawImage(image, 0,0,this); System.out.println(b); } super.paintComponent(g); }}