new JLabel("xxx");
1 package com.kuang.lesson04; 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 public IconDemo(int width,int height){ 14 this.width=width; 15 this.height=height; 16 } 17 18 19 public void init(){ 20 IconDemo iconDemo=new IconDemo(15,15); 21 //图标放在标签,也可以放在按钮上! 22 JLabel label=new JLabel("icontest",iconDemo,SwingConstants.CENTER); 23 24 Container container=getContentPane(); 25 container.add(label); 26 27 this.setVisible(true); 28 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 29 } 30 31 public static void main(String[] args) { 32 new IconDemo().init(); 33 } 34 35 @Override 36 public void paintIcon(Component c,Graphics g,int x,int y){ 37 g.fillOval(x,y,width,height); 38 } 39 @Override 40 public int getIconWidth(){ 41 return this.width; 42 } 43 44 @Override 45 public int getIconHeight(){ 46 return this.height; 47 } 48 49 }
1 package com.kuang.lesson04; 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 label=new JLabel("ImageIcon"); 12 URL url=ImageIconDemo.class.getResource("328583.jpg"); 13 14 ImageIcon imageIcon=new ImageIcon(url); //命名不要重名 15 label.setIcon(imageIcon); 16 label.setHorizontalAlignment(SwingConstants.CENTER); 17 18 Container container=getContentPane(); 19 container.add(label); 20 21 setVisible(true); 22 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 23 setBounds(100,100,100,100); 24 } 25 26 public static void main(String[] args) { 27 new ImageIconDemo(); 28 } 29 }