首页 > 代码库 > Java 窗体背景图+设置按钮样式

Java 窗体背景图+设置按钮样式

这个方法应该是比较麻烦的做法,因为背景图是放在窗体的第二层,如果窗体内容层有很多面板,就得挨个设置透明。话不多说,上代码:

 1 import java.awt.Color;
 2 import java.awt.Dimension;
 3 import java.awt.FlowLayout;
 4 import java.awt.event.WindowAdapter;
 5 import java.awt.event.WindowEvent;
 6 
 7 import javax.swing.ImageIcon;
 8 import javax.swing.JButton;
 9 import javax.swing.JFrame;
10 import javax.swing.JLabel;
11 import javax.swing.JPanel;
12 
13 public class Background extends JFrame {
14     
15     
16     public static void main(String[] args) {
17         new Background();
18     }
19     
20     Background() {    
21         this.setTitle("Background");
22         this.setLayout(new FlowLayout());
23         JButton jb = new JButton("测试");
24         this.add(jb);
25         
26         //放置背景图
27         ImageIcon background = new ImageIcon(Background.class.getClassLoader().getResource("images/img.jpg"));
28         JLabel bkLabel = new JLabel(background);
29         bkLabel.setBounds(0, 0,background.getIconWidth(), background.getIconHeight());
30         this.setSize(background.getIconWidth(), background.getIconHeight());
31         this.getLayeredPane().add(bkLabel,new Integer(Integer.MIN_VALUE));
32         JPanel ctPanel = (JPanel)this.getContentPane();
33         ctPanel.setOpaque(false);
34         
35         //设置按钮样式
36         jb.setPreferredSize(new Dimension(100,40));//设置大小
37         jb.setBackground(new Color(118,238,0));//设置背景色
38         jb.setForeground(Color.WHITE);//设置前景色
39         jb.setFont(new  java.awt.Font("微软楷体",  1,  20)); //设置字体样式
40         
41         this.addWindowListener(new WindowAdapter() {
42             public void windowClosing(WindowEvent arg0) {
43                 System.exit(0);
44             }            
45         });
46         this.setVisible(true);
47     }
48 
49 }

 

 图片放置:(创建的Java项目里的)src > New > Folder > Folder name:images > finish,染回将图片粘贴到images里

效果图:

技术分享

Java 窗体背景图+设置按钮样式