Java中Icon接口的应用(以JLabel为例)


This example shows the drawing of an icon using the Icon interface for the JLable component.

[java]
  1. package com.han;  
  2. import java.awt.*;  
  3. import javax.swing.*;  
  4.   
  5. /** 
  6.  * This example shows the drawing of an icon using the Icon interface 
  7.  *  for the JLable component. 
  8.  * @author han 
  9.  * 
  10.  */  
  11. public class DrawIcon implements Icon{  
  12.     private int width;  
  13.     private int height;  
  14.     @Override  
  15.     public int getIconHeight(){  
  16.         return this.height;  
  17.     }  
  18.     @Override  
  19.     public int getIconWidth(){  
  20.         return this.width;  
  21.     }  
  22.     @Override  
  23.     public void paintIcon(Component c, Graphics g, int x, int y){  
  24.         g.setColor(Color.red);  
  25.         g.fillOval(x, y, width, height);  
  26.     }  
  27.     /*the construct function*/  
  28.     public DrawIcon(int width, int height){  
  29.         this.width=width;  
  30.         this.height=height;  
  31.     }  
  32.     public static void main(String[] args){  
  33.         DrawIcon icon=new DrawIcon(15,15);  
  34.         JLabel jl=new JLabel("测试",icon,SwingConstants.CENTER);  
  35.         JFrame jf=new JFrame();  
  36.         Container c=jf.getContentPane();  
  37.         c.add(jl);  
  38.         jf.setVisible(true);  
  39.         jf.setSize(300,300);  
  40.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  41.     }  
  42. }  

相关内容