Java Reference
In-Depth Information
Creating an Icon
Creating an Icon is as simple as implementing the interface. All you need to do is specify the
size of the icon and what to draw. Listing 4-3 shows one such Icon implementation. The icon is
a diamond-shaped glyph in which the size, color, and filled-status are all configurable.
Tip In implementing the paintIcon() method of the Icon interface, translate the drawing coordinates
of the graphics context based on the x and y position passed in, and then translate them back when the
drawing is done. This greatly simplifies the different drawing operations.
Listing 4-3. Reusable Diamond Icon Definition
import javax.swing.*;
import java.awt.*;
public class DiamondIcon implements Icon {
private Color color;
private boolean selected;
private int width;
private int height;
private Polygon poly;
private static final int DEFAULT_WIDTH = 10;
private static final int DEFAULT_HEIGHT = 10;
public DiamondIcon(Color color) {
this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected) {
this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected, int width, int height) {
this.color = color;
this.selected = selected;
this.width = width;
this.height = height;
initPolygon();
}
private void initPolygon() {
poly = new Polygon();
int halfWidth = width/2;
int halfHeight = height/2;
poly.addPoint(0, halfHeight);
poly.addPoint(halfWidth, 0);
 
Search WWH ::




Custom Search