簡體   English   中英

如何在填充的矩形內繪制字符串?

[英]How to draw a String inside a filled rectangle?

我只想在填充黑色的矩形內顯示我的String。 謝謝您的幫助!

這個給你:

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*/);
  }
}
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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM