为java程序添加漂亮背景图片
信息资料来源:http://topic.csdn.net/t/20050501/21/3980076.html
整理后可执行代码如下:
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class TestBackgroundColor extends JFrame {
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 TestBackgroundColor tbc = new TestBackgroundColor();
8 tbc.setVisible(true);
9 }
10 private JPanel imagePanel;
11 private ImageIcon background;
12
13 public TestBackgroundColor() {
14 background = new ImageIcon("渐变背景14.png");//背景图片
15 JLabel label = new JLabel(background);//把背景图片显示在一个标签里面
16
17 //把标签的大小位置设置为图片刚好填充整个面板
18 label.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
19 //把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
20 imagePanel = (JPanel)this.getContentPane();
21 imagePanel.setOpaque(false);
22 //内容窗格默认的布局管理器为BorderLayout
23 imagePanel.setLayout(new FlowLayout());
24 imagePanel.add(new JButton("测试按钮"));
25
26 this.getLayeredPane().setLayout(null);
27 //把背景图片添加到分层窗格的最底层作为背景
28 this.getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));
29
30 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
31 this.setSize(background.getIconWidth(),background.getIconHeight());
32 this.setVisible(true);
33 }
34 }
效果图如下:


浙公网安备 33010602011771号