The following should get the text centred within the circle:
int spotNameX = spot+100-((g.getFontMetrics().stringWidth(text)/2));
int spotNameY = spot+100;
g.drawString(text, spotNameX, spotNameY);
spot
is the left-most side of the circle (its left-most x
position). If we add 100
to it (half of 200
, i.e. half the width of the circle), we get the x
position in the exact centre of the circle. However, if we were to draw the text here, then it would be too far over - to be centred, half of the text needs to be on the left side, and half needs to be on the right side.
Thus, to properly centre, you need to get the width of the text in pixels, and then divide it in half and subtract that from the previously calculated value.
To put it another way:
(leftmost side + half of width) - (half of width of object to centre) = starting x coord of object to centre
With regards to your other question, it should automatically clear when the paint(Graphics g)
function is called by Swing. If it doesn't, try adding
super.paint(g);
as the first line inside your paint(Graphics g)
function, and that may get it working.