求大神帮忙解决问题,java添加背景图片,程序不稳定,图片经常覆盖控件
做一个java聊天室,添加背景图片后,程序运行经常出现图片覆盖控件,当拖动鼠标时控件一个一个的显示。
下面是添加图片类
public class BackImage extends JPanel{
private static final long serialVersionUID = 1L;
private int width = 0;
private int height = 0;
private String imgPath = "";
public BackImage(int _width,int _height,String _imgPath){
width = _width;
height = _height;
imgPath = _imgPath;
setSize(width,height);
setVisible(true);
}
public void paintComponent(Graphics gs) {
Graphics2D g = (Graphics2D) gs;
super.paintComponent(g);
//画背景图片
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(imgPath));
g.drawImage(image, 0, 0,width,height, this);
}
}
在主程序中添加图片代码是
int panelWidth=this.getWidth();
int panelHeight=this.getHeight();
String path="..\\images\\"+ClientInterface.backimage;
imgPanel = new BackImage(panelWidth,panelHeight,path);
this.jContentPane.add(imgPanel,-1);
------解决方案--------------------直接使用SwingX中的JXPanel,使用setBackgroundPainter + ImagePainter 设置背景。