3

我只想在一个填充黑色的矩形内显示我的字符串。谢谢您的帮助!

4

2 回答 2

8

给你:

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*/);
  }
}
于 2011-11-26T16:54:31.690 回答
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;
}
于 2015-10-19T17:53:08.817 回答