简体   繁体   中英

How to create and set oval icon for the JMenuItem

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:

在此处输入图片说明

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;
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM