This Java tip shows how to implement the Icon interface in Java.

Java Code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class IconInterfaceDemo extends JPanel {

  public IconInterfaceDemo() {

  public static void main(String[] a) {
    JFrame mainFrame = new JFrame();

    JLabel label = new JLabel("label");

    label.setIcon(new ColoredSquare(;
    label.setDisabledIcon(new ColoredSquare(;


    mainFrame.setSize(100, 100);



class ColoredSquare implements Icon {
  Color color;

  public ColoredSquare(Color color) {
    this.color = color;

  public void paintIcon(Component c, Graphics g, int x, int y) {
    Color oldColor = g.getColor();
    g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);

  public int getIconWidth() {
    return 12;

  public int getIconHeight() {
    return 12;