I'm trying to center a circle graphic in a panel.
When I use this code, it works fine:
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);
}
But I want to use this code (below), with xCoordinate and yCoordinate as arguments for x and y because I need the variables for other method uses in the class. But when I use the code below, The circle begins in the upper left corner, with only the bottom left portion of the circle in the frame.
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);
}
}
Why does it cause this problem when using the variables as arguments, and what can I do to fix it?
The panel's width and height vary between the moment the panel is created and the moments it's shown, enlarged, reduced. So you should always get the current width and current height, as you're doing in your first example, to get the right one.
You shouldn't change the yCoordinate in moveUp()
. You should change an offset from the original coordinate:
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;
}