想在继承JPanel中用一个背景图片,先来看一下代码
public class MyBanner extends JPanel{
??? private static final long serialVersionUID = 1L;
??? Image bg;
??? public MyBanner()
??? {
??? ??? bg=new ImageIcon("image/banner.png").getImage();
??? }
}
刚开始我只是这样弄,可是这样背景图片显示不出来,后来我发现要重载paint方法,在这里面重新画,修改后的代码是
?
public class MyBanner extends JPanel{
??? /**
??? ?*
??? ?*/
??? private static final long serialVersionUID = 1L;
??? Image bg;
??? public MyBanner()
??? {
??? ??? setOpaque(false);//设置透明色
?? 这个不能少,不然也会看不到效果
??? ??? bg=new ImageIcon("image/banner.png").getImage();
??? }
??? @Override
??? public void paint(Graphics g) {
??? ??? g.drawImage(bg,0,40,bg.getWidth(null)+300,bg.getHeight(null)-30,null);
??? ??? super.paint(g);
??? }
}