如何在Java中绘制一个实心圆?

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

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( 链接 )的文档。

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

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

 /***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);