2011-11-26 64 views
3

我只想在充滿黑色的矩形內顯示我的字符串。謝謝您的幫助!如何在填充矩形內繪製字符串?

+2

你嘗試過這麼遠嗎? 'drawString()'可以做到,但一定要在繪製矩形後調用它,否則會覆蓋字符串。 – zeller

+0

我已經嘗試了g.fill之前的drawString,但它不是我正在尋找的。如果在g.fill之後,我嘗試過,它仍然不是D: – alicedimarco

+0

也許在drawString之前改變顏色? – zeller

回答

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

如果我有g.drawRect(x-50,y-50,60,25),你認爲我的座標應該用於drawString嗎? – alicedimarco

+0

Nvm! :D我知道了。非常感謝!我想通了:)哈哈我只是很難與我的drawString的座標,所以它沒有中心。 – alicedimarco

+1

我很高興它的工作:) – GETah

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; 
} 
+0

你'字體的字體= g2.getFont();'然後兩行之後的'g2.setFont(字體);'不與變量'font'做任何事情。是不是'setFont'多餘? – 11684