user591790
user591790

Reputation: 555

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.

Upvotes: 0

Views: 2177

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Paint the label to a BufferedImage, paint the rectangle, then the image.

Upvotes: 1

user837703
user837703

Reputation:

Like Mark Bramnik has said, there are a bunch of different ways to do this, paintComponent is one, but not the best. If you're not putting too many components into your JPanel you can use a null layout while overriding the paintComponent for your coloring like this:

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

Beware, you have to set the coordinates for every component you put in the JPanel. Null layouts are explained in more detail here.

If you must override the paintComponent method, you can do something like this:

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

Maybe ugly, but doable (also, the code isn't tested, but should work).

A cleaner way could be the JLayeredPane or if you are using JDK 1.7.0 the JLayer.

Good luck!

Upvotes: 0

Mark Bramnik
Mark Bramnik

Reputation: 42541

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

Upvotes: 5

Related Questions