Question

I wanted to create JMenu with an oval icon for my JMenuItem

So I know I should use:

JMenuItem item = new JMenuItem(title);
item.setIcon(icon)

But how to create that kind of icon:

enter image description here

Was it helpful?

Solution

You could make your own Icon-implementation:

public class OvalIcon implements Icon {
    private int width;
    private int height;
    private Color color;

    public OvalIcon(int w, int h, Color color) {
        if((w | h) < 0) {
            throw new IllegalArgumentException("Illegal dimensions: "
                    + "(" + w + ", " + h + ")");
        }
        this.width  = w;
        this.height = h;
        this.color  = (color == null) ? Color.BLACK : color;
    }
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Color temp = g.getColor();
        g.setColor(color);
        g.fillOval(x, y, getIconWidth(), getIconHeight());
        g.setColor(temp);
    }
    @Override
    public int getIconWidth() {
        return width;
    }
    @Override
    public int getIconHeight() {
        return height;
    }
}

OTHER TIPS

Playing With Shapes provides you with a ShapeIcon which allows you to create Icons of many different shapes. For example:

Shape round = new Ellipse2D.Double(0, 0, 10, 10);
ShapeIcon red = new ShapeIcon(round, Color.RED);
ShapeIcon green = new ShapeIcon(round, Color.GREEN);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top