本文介绍了画一个标签,包含一个显示一个圆圈的图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I am trying to draw a label which contains an icon showing a circle. The circle will initially be filled red, and then depending on which of the 3 buttons I press, it will either change to green, blue, or red using repaint.

这里是我到目前为止:

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。有没有不同的方法来做到这一点?我很感激任何帮助。

My issue is, I have no idea what to pass for the Graphics g in paintIcon. Is there a different way to do this? I appreciate any help with this.

推荐答案

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

图标的大小为(10,10)。 50,超出了Icon的范围。绘画是相对于图标完成的,因此椭圆应为:

The size of the icon is (10, 10). 50, is outside the bounds of the Icon. Painting is done relative to the icon so the ellipse should be:

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



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

Your ColorChanger class will need a setColor(Color color) method so that you can dynamically change the color to be painted. The paintIcon() method should then use this color.

这篇关于画一个标签,包含一个显示一个圆圈的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 20:19