绘制包含显示圆圈的图标的标签

Drawing a Label Containing an Icon Showing a Circle

所以我正在尝试绘制一个标签,其中包含一个显示圆圈的图标。圆圈最初会填充红色,然后根据我按下的 3 个按钮中的哪一个,使用重绘将其变为绿色、蓝色或红色。

这是我目前的情况:

public class ColorChanger implements Icon {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame myFrame = new JFrame();
        JButton redButton = new JButton("Red");
        JButton greenButton = new JButton("Green");
        JButton blueButton = new JButton("Blue");
        Graphics g;

        ColorChanger myCircle = new ColorChanger();
        final JLabel myLabel = new JLabel(myCircle);

    //  myCircle.paintIcon(myFrame, g, 50, 50);

        final int FRAME_WIDTH = 300;
        final int FRAME_HEIGHT = 200; 

        myFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        myFrame.setLayout(new FlowLayout());

        myFrame.add(redButton);
        myFrame.add(greenButton);
        myFrame.add(blueButton);
        myFrame.add(myLabel);

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        myFrame.pack();
        myFrame.setVisible(true); 
    }

    @Override
    public int getIconWidth() {
        // TODO Auto-generated method stub
        return 10;
    }

    @Override
    public int getIconHeight() {
        // TODO Auto-generated method stub
        return 10;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        // TODO Auto-generated method stub
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 10, 10);
        g2.setColor(Color.RED);
        g2.fill(circle);
    }    
}

我的问题是,我不知道要为 paintIcon 中的 Graphics g 传递什么。有没有不同的方法来做到这一点?感谢您对此提供的任何帮助。

Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 10, 10);

图标的大小为(10, 10)。 50,在图标的范围之外。绘画是相对于图标完成的,所以椭圆应该是:

Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 10, 10);

it will either change to green, blue, or red using repaint.

您的 ColorChanger class 需要一个 setColor(Color color) 方法,以便您可以动态更改要绘制的颜色。然后 paintIcon() 方法应该使用这种颜色。