如何在Java中绘制实心圆?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2509561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:38:16  来源:igfitidea点击:

How to draw a filled circle in Java?

javauser-interfaceswinggraphicsgeometry

提问by Roman

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.

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

采纳答案by Roman

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);
   ...
}

Here are some docs about paintComponent (link).

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

You should override that method in your JPanel and do something similar to the code snippet above.

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

In your ActionListener you should specify x, y, diameterand call repaint().

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

回答by M_R_K

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