如何为JMenuItem创建和设置椭圆形图标

时间:2013-05-25 16:51:37

标签: java swing icons jmenuitem

我想为我的JMenuItem

创建一个带有椭圆形图标的JMenu

所以我知道我应该使用:

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

但是如何创建这种图标:

enter image description here

2 个答案:

答案 0 :(得分:6)

您可以制作自己的Icon - 实施:

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

答案 1 :(得分:2)

Playing With Shapes为您提供ShapeIcon,可让您创建多种不同形状的图标。例如:

Shape round = new Ellipse2D.Double(0, 0, 10, 10);
ShapeIcon red = new ShapeIcon(round, Color.RED);
ShapeIcon green = new ShapeIcon(round, Color.GREEN);