该程序在 jPanel 上绘制两个输入大小的圆,一个在另一个之上。问题是,两个圆不居中。我该如何解决这个问题?
代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel.Repaint();
try{
jLabel6.setText("");
int a=Integer.parseInt(jTextField1.getText());
Graphics2D gfx=(Graphics2D)jPanel1.getGraphics();
gfx.clearRect(0, 0, getWidth(), getHeight());
gfx.setColor(Color.red);
gfx.fillOval(100,50,a,a);
gfx.fillOval(100,50,a,a);
}catch(NumberFormatException e){
jLabel6.setText("Incorrect data");
}
}
结果:
最佳答案
The problem is, the two circles are not centered.
您必须了解 Swing 自定义绘图中的 x、y 坐标如何工作来定位组件。
尝试理解下面的屏幕截图。
<小时/>
在原x
中添加width/2
,根据椭圆的宽度获取居中的x
坐标。
对高度也执行相同的操作。
示例代码:
int x = 50;
int y = 50;
int size = 100;
g.setColor(Color.red);
g.fillOval(x, y, size, size);
int center = x + size / 2;
size = 70;
g.setColor(Color.blue);
g.fillOval(center - size / 2, center - size / 2, size, size);
关于java - 绘图 : centering objects of different size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714810/