【问题标题】:How to draw a filled circle in Java?如何在Java中绘制一个实心圆?
【发布时间】:2011-01-31 08:39:29
【问题描述】:

我有一个带有网格布局的 JPanel。在网格的“单元格”中,我可以放置不同的元素(例如 JButtons)。没有问题。但现在我想在一些单元格中放置一个实心圆圈。我还想将 ActionListener 与这些圈子联系起来。更详细地说,如果我单击圆圈,它将从当前单元格中消失并出现在另一个单元格中。我怎样才能在Java中做到这一点?我正在使用 Swing。

【问题讨论】:

    标签: java user-interface swing graphics geometry


    【解决方案1】:
    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Graphics2D g2d = (Graphics2D)g;
       // Assume x, y, and diameter are instance variables.
       Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
       g2d.fill(circle);
       ...
    }
    

    这里有一些关于paintComponent (link) 的文档。

    您应该在 JPanel 中覆盖该方法并执行类似于上面的代码 sn-p 的操作。

    在您的 ActionListener 中,您应该指定 x, y, diameter 并调用 repaint()

    【讨论】:

    • 嘿,我以为这是一个自我回答。
    • @mmyers:是的,这有点令人困惑))
    • @Roman Link 现在已经死了。 Is this a suitable replacement?
    【解决方案2】:
    /***Your Code***/
    public void paintComponent(Graphics g){
    /***Your Code***/
        g.setColor(Color.RED);
        g.fillOval(50,50,20,20);
    }
    
    g.fillOval(x-axis,y-axis,width,height);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2021-01-30
      • 2019-01-21
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多