Search code examples
javaswinggraphicsjlabelpaintcomponent

how to put the JLabel inside the rectangle


I have created a rectangle now I have to put one JLabel into this. so how can i put the JLabel inside the rectangle.

Code here :-

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

please give me some idea to implement this.

thanks in advance.


Solution

  • There are a lot of ways to achieve the similar result. You shouldn't really use your approach however. Use paintComponent as you use it to really paint and don't put swing components on it, I believe its more clear approach.

    You can use JLayeredPane, and place your label in one layer and your drawing on the other one.

    I would consider also using Borders in your label - maybe you won't need the rectangle at all in this case. See the example here: Labels with Borders

    Hope this helps