最近在写Swing的程序,对怎么在在Jpanel上放置背景网上大多数是在上面加个JLabel,然后设置JLAbel的Icon!但这样做后,JPanel上加其它组件就不好处理了!于是想到继承JPanel然后再重写paintComponent(Graphics g)和paintChildren(Graphics g)这两个方法,这样就保证了JPanel,最初的状态,想怎么处理其它组件都行了;以下是源代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class BackGroundPane extends JPanel {
private ImageIcon imageIcon;
public ImageIcon getImageIcon() {
return imageIcon;
}
public void setImageIcon(ImageIcon imageIcon) {//设置图片
this.imageIcon = imageIcon;
}
public BackGroundPane() {
super();
this.setOpaque(false);
}
protected void paintChildren(Graphics g) {//重绘JPanel下的Components
super.paintChildren(g);
for(int i =0;i<this.getComponents().length;i++){
this.getComponent(i).repaint();
}
g.dispose();
}
protected void paintComponent(Graphics g) {
Graphics2D g2D = (Graphics2D)g;
super.paintComponent(g2D);
if(imageIcon!=null){//绘制背景
g2D.drawImage(imageIcon.getImage(), 0, 0,this.getWidth(),this.getHeight(),this);
}
g2D.dispose();
}
}
在调用的时候只要新建一个对象,然后再调用setImageIcon(ImageIcon imageIcon)方法就是可以绘制背景了,如果没有背景也可以当JPanel!!