問題描述
我有一個帶有網格布局的 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中繪制一個實心圓?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!