Java Swing How to - Extend Icon to draw custom icon for JButton








Question

We would like to know how to extend Icon to draw custom icon for JButton.

Answer

/*w w  w. java 2 s .c om*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

  public static void main(String args[]) {
    JFrame frame = new JFrame("");
    Container contentPane = frame.getContentPane();
    Icon icon = new PieIcon(Color.red);
    JButton b = new JButton("Button!", icon);
    contentPane.add(b, BorderLayout.NORTH);
    b = new JButton(icon);
    contentPane.add(b, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.show();
  }
}

class PieIcon implements Icon {
  Color color;

  public PieIcon(Color c) {
    color = c;
  }

  public int getIconWidth() {
    return 20;
  }

  public int getIconHeight() {
    return 20;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.fillArc(x, y, getIconWidth(), getIconHeight(), 45, 270);
  }
}