【问题标题】:Drawing a Label Containing an Icon Showing a Circle绘制包含显示圆圈的图标的标签
【发布时间】:2015-03-06 05:43:50
【问题描述】:

所以我正在尝试绘制一个标签,其中包含一个显示圆圈的图标。圆圈最初会被填充为红色,然后根据我按下的 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 中的图形 g 传递什么。有不同的方法可以做到这一点吗?感谢您对此提供的任何帮助。

【问题讨论】:

  • 图标会在需要更新时由JLabel自动绘制...
  • @MadProgrammer 但它不是在画它。我要显示 3 个按钮,但现在是圆圈。
  • 一个完整的例子显示在here
  • @trashgod 谢谢!这看起来是一个非常有用的帖子。我一定会在我的工作时参考它。

标签: java swing icons


【解决方案1】:
Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 10, 10);

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

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

它会通过重绘变为绿色、蓝色或红色。

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

【讨论】:

  • @aurora91,很高兴它有帮助。你应该“接受”答案,这样人们就知道问题已经解决了。
  • 完成了。感谢@AndrewThompson 的链接。老实说,我不确定“接受”按钮在哪里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
相关资源
最近更新 更多