gpt4 book ai didi

java - 使用变量作为 x、y 参数在面板中以圆为中心

转载 作者:行者123 更新时间:2023-12-02 06:46:50 24 4
gpt4 key购买 nike

我正在尝试将圆形图形置于面板的中心。

当我使用此代码时,它工作正常:

private int radius = 50;
private ballSize = radius * 2;

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(getWidth()/2 - radius,
getHeight()/2 - radius, ballSize, ballSize);
}

但是我想使用这段代码(如下),其中 xCooperative 和 yCooperative 作为 x 和 y 的参数,因为我需要类中其他方法使用的变量。但是当我使用下面的代码时,圆圈从左上角开始,框架中只有圆圈的左下部分。

private class BallPanel extends JPanel {
private int radius = 50;
private int xCoordinate = getWidth() / 2 - radius;
private int yCoordinate = getHeight() / 2 - radius;
private int ballSize = radius * 2;

public void moveUp() {
if (yCoordinate > 0 - radius) {
yCoordinate--;
repaint();
}
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(xCoordinate, yCoordinate,
radius * 2, radius * 2);
}
}

为什么在使用变量作为参数时会导致此问题,我该如何解决它?

最佳答案

面板的宽度和高度在面板创建时和显示、放大、缩小时会发生变化。因此,您应该始终获取当前宽度和当前高度,就像您在第一个示例中所做的那样,以获得正确的宽度和高度。

您不应该在 moveUp() 中更改 y 坐标。您应该更改原始坐标的偏移量:

private int yOffset = 0;
private int ballSize = radius * 2;

public void moveUp() {
if (computeY() > 0 - radius) {
yOffset--;
repaint();
}
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(getWidth() / 2 - radius, computeY(), ballSize, ballSize);
}

private int computeY() {
return (getHeight() / 2 - radius) + yOffset;
}

关于java - 使用变量作为 x、y 参数在面板中以圆为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548753/

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