How to draw a filled circle in Java?(如何在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 的文档(链接).
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中绘制一个实心圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在Java中绘制一个实心圆?


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01