2012-06-28 56 views
0

我已经创建了一个矩形,现在我必须将一个JLabel放入此矩形中。所以如何将JLabel放在矩形内。如何将JLabel放在矩形内

代码在这里: -

public class ColoredRect extends JPanel 
{ 

    private double x, y, width, height; 

    public ColoredRect(double x,double y) 
    { 
      this.x = x; 
      this.y = y; 
      width = 100; 
      height =40; 
      rect = new Rectangle2D.Double(this.x , this.y,width,height); 
    } 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setColor(Color.cyan); 
     g2.fill(rect); 
    } 
} 

,请给我一些想法实现这一点。

在此先感谢。

回答

5

有很多方法可以达到类似的结果。但是,你不应该真的使用你的方法。在使用paintComponent的时候使用paintComponent来绘制真实颜色,并且不要在其上放置摆动组件,我相信它更加清晰。

您可以使用JLayeredPane,并将您的标签放在一个图层中,并将您的图纸放在另一个图层上。

我会考虑在你的标签中使用边框 - 也许在这种情况下你根本不需要矩形。 看到这里的例子:Labels with Borders

希望这有助于

+0

感谢马克的快速回复......但我必须使长方形像微软visio所以用户可以编辑文本到矩形。 – user591790

0

像马克Bramnik说,有一堆不同的方式做到这一点,paintComponent是其中之一,但不是最好的。如果你不把太多的组件集成到您的JPanel你可以使用一个空的布局,而重写paintComponent您的着色是这样的:

this.setLayout(null); 
//...when you get to adding your JLabel... 
this.add(theJLabel); 
theJLabel.setBounds(x, y, width, height); 

当心,你必须设置你把每个组件的坐标JPanel的。更详细地解释空布局here

如果你必须重写paintComponent方法,你可以做这样的事情:

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics g2 = g.create(); 
    theJLabel.setPreferredSize(new Dimension(width, height)); 
    g2.translate(x, y); 
    theJLabel.paint(g2); 
    g2.dispose(); 
} 

也许丑陋,但可行的(也,代码没有经过测试,但应工作)。

更清洁的方式可能是JLayeredPane或者如果您使用JDK 1.7.0 JLayer

祝你好运!

1

将标签绘制到BufferedImage,绘制矩形,然后绘制图像。