其他分享
首页 > 其他分享> > GUI-Swing-图标Icon

GUI-Swing-图标Icon

作者:互联网

图标Icon

方法一:

 1 package com.luckylu.gui;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5 
 6 public class IconDemo extends JFrame implements Icon {
 7 
 8     private int width;
 9     private int height;
10     //无参构造,图片可以选择无参
11     public IconDemo(){
12     }
13 
14     //有参构造,图片可以选择有参
15     public IconDemo(int width, int height){
16         this.width = width;
17         this.height = height;
18     }
19 
20     public void init(){
21         IconDemo iconDemo = new IconDemo(15,15);
22         //图标可以放在标签上,也可以放在按钮上;
23         JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
24 
25         Container container = getContentPane();
26         container.add(label);
27 
28         this.setVisible(true);
29         this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
30 
31 
32     }
33 
34     public static void main(String[] args) {
35         new IconDemo().init();
36 
37     }
38     @Override
39     public void paintIcon(Component c, Graphics g, int x, int y) {
40         g.fillOval(x,y,width,height);  //实心圆
41     }
42 
43     @Override
44     public int getIconWidth() {
45         return this.width;  //文本右移的距离
46     }
47 
48     @Override
49     public int getIconHeight() {
50         return this.height;  //文本下移的距离
51     }
52 }

结果:

 

 

方法二:插入图片Icon

 1 package com.luckylu.gui;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5 import java.net.URL;
 6 
 7 public class ImageIconDemo extends JFrame {
 8 
 9     public ImageIconDemo() {
10         //获取图片的地址
11         JLabel jlabel = new JLabel("辽宁本钢LOGO");  //注意是 JLable
12         URL url = ImageIconDemo.class.getResource("ICON.png");  //图片连接
13 
14         ImageIcon imageIcon = new ImageIcon(url);
15         jlabel.setIcon(imageIcon);  //插入库图片
16         jlabel.setHorizontalAlignment(SwingConstants.CENTER);  //居中
17 
18         //设置一个容器
19         Container container = getContentPane();
20         container.add(jlabel); // 将jlabel 写入容器
21 
22         setVisible(true);
23         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
24         setBounds(200,200,400,260);
25 
26     }
27     public static void main(String[] args) {
28         new ImageIconDemo();
29     }
30 }

结果:

 

标签:int,GUI,IconDemo,height,width,Swing,new,public,Icon
来源: https://www.cnblogs.com/luckylu/p/16164721.html