Rom*_*man 15 java graphics user-interface geometry swing
我有一个带网格布局的JPanel.在网格的"单元格"中,我可以放置不同的元素(例如JButtons).没有问题.但是现在我想在一些细胞中放一个圆圈.我还想将ActionListener与这些圈子联系起来.更详细地说,如果我单击圆圈,它将从当前单元格中消失并显示在另一个圆圈中.我怎么能用Java做呢?我正在使用Swing.
Rom*_*man 29
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);
...
}
Run Code Online (Sandbox Code Playgroud)
这里有一些关于paintComponent(链接)的文档.
您应该在JPanel中覆盖该方法,并执行与上面的代码段类似的操作.
在ActionListener中,您应该指定x, y, diameter并调用repaint().
M_R*_*R_K 12
/***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);
Run Code Online (Sandbox Code Playgroud)