user3456343 user3456343 - 1 month ago 22
Java Question

How to write text inside a rectangle

Hi I am creating a java desktop application where I am drawing rectangle. I want to write some text inside rectangle.

How can I achieve this?

Here is my code:

class DrawPanel extends JPanel {

private void doDrawing(Graphics g) {
int a=90;
int b=60;
int c=10;
int d=15;


ArrayList<Graphics2D> g1 = new ArrayList<Graphics2D>();
for(int i=0;i<=9;i++){

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(c, d, a, b);



d+=65;
}
}

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);
}
}

Answer

Use your Graphics2D object and call drawString(String str, int x, int y). Something like

 g2d.drawRect(c, d, a, b);
 g2d.drawString("Hi", (a+c)/2, (b+d)/2);

Note that the Javadoc specifies

Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system.

so you would need to take into account the space the font takes on screen. Use FontMetrics for that,

Comments