gpt4 book ai didi

java - 绘图 : centering objects of different size

转载 作者:行者123 更新时间:2023-12-01 22:58:23 25 4
gpt4 key购买 nike

该程序在 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");
}
}

结果:
enter image description here

最佳答案

The problem is, the two circles are not centered.

您必须了解 Swing 自定义绘图中的 x、y 坐标如何工作来定位组件。

尝试理解下面的屏幕截图。

enter image description here

<小时/>

在原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);

enter image description here

关于java - 绘图 : centering objects of different size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com