如何在Java中绘制实心圆? [英] How to draw a filled circle in Java?
问题描述
我有一个带有网格布局的JPanel。在网格的单元格中,我可以放置不同的元素(例如JButtons)。这没有问题。但是现在我想在一些单元格中填充一个实心圆。我也想将ActionListener与这些圈子联系起来。更详细地说,如果我点击圆圈,它会从当前单元中消失,并出现在另一个单元格中。我怎样才能在Java中做到这一点?我使用Swing。
I have a JPanel with a Grid Layout. In the "cells" of the grid I can put different elements (for example JButtons). There is no problems with that. But now I want to put a filled circle in some of the cells. I also would like to relate an ActionListener with these circles. In more details, if I click the circle it disappears from the current cell and appears in another one. How can I do it in Java? I am using 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的文档( link ) 。
Here are some docs about paintComponent (link).
您应该在您的JPanel中重写该方法,并执行与上面的代码片段类似的操作。
You should override that method in your JPanel and do something similar to the code snippet above.
你的ActionListener你应该指定 x,y,diameter
并且调用 repaint()
。
In your ActionListener you should specify x, y, diameter
and call repaint()
.
这篇关于如何在Java中绘制实心圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!