在这里主要通过继承JPanel来定义一个backgoundPanel类,将其添加到JFrame中,来给他设置背景,这样做的好处是我们还可以在上面继续添加其他组件,如下(BackgruondPanel):
public class BackgruondPanel extends JPanel{
private ImageIcon pic;
private Image image;
private int width;
private int height;
public BackgruondPanel(String imgUrl) {
pic = new ImageIcon(imgUrl);
image = pic.getImage();
width = pic.getIconWidth();
height = pic.getIconHeight();
this.setSize(width, height);
}
@Override
public void paint(Graphics arg0) {
super.paint(arg0);
arg0.drawImage(image, 0, 0, width, height,null);
}
//获取作为背景图片的宽度
public int getdefaultWidth(){
return width;
}
//获取作为背景图片的高度
public int getdefaultHeight(){
return height;
}
}
main类:
public class Main {
public static void main(String[] args) {
initView();
}
public static void initView(){
String url = "img\\main_background.gif";
JFrame frame = new JFrame();
BackgruondPanel bgpanel = new BackgruondPanel(url);
frame.add(bgpanel);
frame.setBounds(30, 30, bgpanel.getdefaultWidth(), bgpanel.getdefaultHeight());
//设置去掉边框
frame.setUndecorated(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}