0

So I have an oval and I want to be able to put my name in it so that when I move the oval the name stays in the middle.

Also when I repaint(), how do I clear what's there first, so there aren't multiple objects?

Here is my current code:

public void paint(Graphics g)
{

    g.setColor(Color.GREEN);
    g.drawOval(spot, spot, 200, 200);

    int spotName = spot +60;
    int spotName_2 = spot_2 + 100;
    String text = "Name";
    g.drawString(text, spotName, spotName_2);


    //add image
    g.drawImage(image, 0, 0, this);

 }
Samuel Fipps
  • 193
  • 1
  • 13

1 Answers1

2

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.

Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55