import java.awt.*;
import javax.swing.*;
public class BackgroundImg extends JFrame{
public static void main(String[] args){
new BackgroundImg();
}
JPanel jp_window;//添加所有组件的面板
JLabel lable_img;//图片标签
private static final ImageIcon bgimg = new ImageIcon("image/Scenery.jpg");//背景图片
public BackgroundImg(){
JLabel lable_img = new JLabel(bgimg);//把背景图片显示在一个标签里面
//把标签的大小位置设置为图片刚好填充整个面板
lable_img.setBounds(0,0,bgimg.getIconWidth(),bgimg.getIconHeight());
//把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
jp_window = (JPanel)this.getContentPane();
jp_window.setOpaque(false);//设置面板的透明度
//内容窗格默认的布局管理器为BorderLayout
/*
* 所有组件直接添加到jp_window 面板中就可以了
* */
jp_window.setLayout(new FlowLayout());
jp_window.add(new JPanel().add(new JButton("测试按钮")));
jp_window.add(new JLabel("测试标签"));
//用于实现窗口背景图片
this.getLayeredPane().setLayout(null);
//把背景图片添加到分层窗格的最底层作为背景
this.getLayeredPane().add(lable_img,new Integer(Integer.MIN_VALUE));
/*
* 这里不清楚原因,得不到图片的正确高度,但是方法没有错:getIconHeight()
* 建议根据图片的大小设置窗口大小
* */
this.setSize(bgimg.getIconWidth(),bgimg.getIconHeight());//得到图片的宽和高
//this.setResizable(false);//设置窗口的不可最大化
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
}
测试截图: