3

I just want to display my String inside a rectangle filled with black. Thanks for the help!

alicedimarco
  • 325
  • 1
  • 5
  • 20
  • 2
    What have you tried so far? `drawString()` can do it, but be sure to call it after the rect is drawn, otherwise it will cover the string. – zeller Nov 26 '11 at 16:53
  • I've tried putting drawString before g.fill but it's not what I'm looking for. I tried putting if after g.fill, it's still not it D: – alicedimarco Nov 26 '11 at 18:01
  • Maybe chage the color before the drawString? – zeller Nov 26 '11 at 18:11

2 Answers2

8

Here you are:

public class MyPanel extends JPanel{
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(10/*x*/, 10/*y*/, 80/*width*/, 30/*hight*/);
    g.drawString("TextToDraw", 25/*x*/, 25/*y*/);
  }
}
GETah
  • 20,922
  • 7
  • 61
  • 103
  • What do you think my coordinates should be for drawString if I have g.drawRect(x-50, y-50, 60, 25) ? – alicedimarco Nov 26 '11 at 18:06
  • Nvm! :D I got it. Thank you so much! I figured it out :) lol I was just having a hard time with the coordinates for my drawString so it didn't center. – alicedimarco Nov 26 '11 at 18:12
2
public class LabeledRectangle extends Rectangle{

    public LabeledRectangle(int x, int y, int width, int height, String text) {
        super (x, y, width, height);
        this.text = text;

    }

    public void draw(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(new Rectangle2D.Double(x, y, width,height));
        Font font = g2.getFont();
        FontRenderContext context = g2.getFontRenderContext();
        g2.setFont(font);
        int textWidth = (int) font.getStringBounds(text, context).getWidth();
        LineMetrics ln = font.getLineMetrics(text, context);
        int textHeight = (int) (ln.getAscent() + ln.getDescent());
        int x1 = x + (width - textWidth)/2;
        int y1 = (int)(y + (height + textHeight)/2 - ln.getDescent());

        g2.setColor(Color.red);

        g2.drawString(text, (int) x1, (int) y1);
    }
    private String text;
}
11684
  • 7,356
  • 12
  • 48
  • 71
BBsal
  • 45
  • 6
  • You have `Font font = g2.getFont();` and then two lines later `g2.setFont(font);` without doing anything with the variable `font`. Isn't the `setFont` redundant? – 11684 Jul 30 '17 at 23:36