State-Aware Icon Definition : Icon « Swing « Java Tutorial

State-Aware Icon Definition
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

class DiamondAbstractButtonStateIcon implements Icon {
  public DiamondAbstractButtonStateIcon() {

  public int getIconHeight() {
    return 20;

  public int getIconWidth() {
    return 20;

  public void paintIcon(Component component, Graphics g, int x, int y) {
    if (component instanceof AbstractButton) {
      AbstractButton abstractButton = (AbstractButton) component;
      boolean selected = abstractButton.isSelected();

      if (selected) {
      } else {
      g.drawRect(0, 0, 20, 20);

public class DiamondAbstractButtonStateIconDemo {

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

    JCheckBox bn = new JCheckBox("Click to change the icon color");
    bn.setIcon(new DiamondAbstractButtonStateIcon());


    frame.setSize(300, 200);


14.116.1.Creating an Icon(implement Icon interface)
14.116.2.State-Aware Icon DefinitionState-Aware Icon Definition
14.116.3.implements Icon, SwingConstants
14.116.4.Demonstrate the loading of image files into icons for use in a Swing user interface
14.116.5.An empty icon with arbitrary width and height.
14.116.6.An icon for painting a square swatch of a specified Color.
14.116.7.Arrow Icon
14.116.8.Creates a transparent icon.
14.116.9.Layered Icon