Icon标签:


1 package com.gui.lesson4;
2
3 import javax.swing.*;
4 import java.awt.*;
5
6 //图标,需要实现类,Frame继承
7 public class IconDemo extends JFrame implements Icon {
8
9 private int width;
10 private int height;
11
12 public IconDemo() {//无参构造
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 public static void main(String[] args) {
34 new IconDemo().init();
35 }
36
37 @Override
38 public void paintIcon(Component c, Graphics g, int x, int y) {
39 g.fillOval(x, y, width, height);
40 }
41
42 @Override
43 public int getIconWidth() {
44 return this.width;
45 }
46
47 @Override
48 public int getIconHeight() {
49 return this.height;
50 }
51 }
ImageIcon标签:


1 package com.gui.lesson4;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.net.URL;
6
7 public class ImageIconDemo extends JFrame {
8 public ImageIconDemo() {
9 //获取图片的地址
10 JLabel label = new JLabel("ImageIcon");
11 URL url = ImageIconDemo.class.getResource("tx.jpg");
12 ImageIcon imageIcon = new ImageIcon(url);
13 label.setIcon(imageIcon);
14 label.setHorizontalAlignment(SwingConstants.CENTER);
15
16 Container contentPane = getContentPane();
17 contentPane.add(label);
18
19 setBounds(100, 100, 300, 300);
20 setVisible(true);
21 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
22 }
23
24 public static void main(String[] args) {
25 new ImageIconDemo();
26 }
27 }