2014-03-25 29 views
1

嗨我正在创建一个Java桌面应用程序,我正在绘制矩形。我想在矩形内写一些文字。如何在矩形内写文本

我该如何做到这一点?

这里是我的代码:

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); 
    } 
} 
+1

doDrawing关于Graphics2D的一切应该在paintComponent中,在doDrawing中只创建坐标,对象,在paintComponent里面只能在准备好的对象内部循环arrray – mKorbel

+1

使用['drawString'](http://docs.oracle.com/ javase/7/docs/api/java/awt/Graphics.html#drawString(java.lang.String,int,int))方法。在'drawRect'之后。 – alex2410

+1

还要考虑'TextLayout',见[这里](http://stackoverflow.com/a/4287269/230513)。 – trashgod

回答

3

使用您的Graphics2D对象,并调用drawString(String str, int x, int y)。像

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

注意一些的Javadoc指定

绘制由指定的字符串给出的文本,用此图形上下文的当前字体和颜色。最左边字符的基线位于此图形上下文坐标系中的位置(x,y)处。

所以你需要考虑字体在屏幕上的空间。为此,使用FontMetrics

+0

什么是+ c/2这里 – user3456343

+0

这是你定义的a和c,它只是一个例子,我不知道你是否想要你的字符串。 – user1803551

+0

y参数drawString设置字符串的基线,(b + d)/ 2将垂直对齐字符串基线到中心,而不是文本本身。 –

相关问题