java窗口添加背景

 1 1.import javax.swing.ImageIcon;  
 2 2.import javax.swing.JFrame;  
 3 3.import javax.swing.JLabel;  
 4 4.import javax.swing.JPanel;  
 5 5.public class MainJFrame extends JFrame {  
 6 6.  
 7 7.    public MainJFrame() {  
 8 8.        //设置标题   
 9 9.        super("JFram设置背景图片(Cannel_2020)");  
10 10.        //设置大小   
11 11.        setSize(500, 400);  
12 12.        //设置位置   
13 13.        setLocation(200, 50);  
14 14.        //背景图片的路径。(相对路径或者绝对路径。本例图片放于"java项目名"的文件下)   
15 15.        String path = "background.jpg";  
16 16.        // 背景图片   
17 17.        ImageIcon background = new ImageIcon(path);  
18 18.        // 把背景图片显示在一个标签里面   
19 19.        JLabel label = new JLabel(background);  
20 20.        // 把标签的大小位置设置为图片刚好填充整个面板   
21 21.        label.setBounds(0, 0, this.getWidth(), this.getHeight());  
22 22.        // 把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明   
23 23.        JPanel imagePanel = (JPanel) this.getContentPane();  
24 24.        imagePanel.setOpaque(false);  
25 25.        // 把背景图片添加到分层窗格的最底层作为背景   
26 26.        this.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));  
27 27.        //设置可见   
28 28.        setVisible(true);  
29 29.        //点关闭按钮时退出   
30 30.        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
31 31.    }  
32 32.  
33 33.    public static void main(String[] args) {  
34 34.        new MainJFrame();  
35 35.    }  
36 36.}  
原文地址:https://www.cnblogs.com/zyb993963526/p/6170045.html