-3

Possible Duplicate:
Centering a JLabel on a JPanel

i want to put JLabel in to the center of JPanel. i have used below code so can you just tell me. what is wrong with this code? code :

public class ColoredRect extends JPanel{

      public double x, y, width, height;  
      public JLabel name;

      public ColoredRect(double x,double y,String label)
      {

          this.x = x;
          this.y = y;
          this.width = 100;
          this.height =40;

          setLocation((int)x,(int)y);
          setSize((int)width,(int)height);
          setBackground(Color.red);

          name = new JLabel(label,JLabel.CENTER);
          name.setForeground(Color.BLACK);
          name.setVisible(true);
          name.setSize(20,20);
          name.repaint();
          add(name);
        }
}

thanks in advance

Community
  • 1
  • 1
user591790
  • 545
  • 2
  • 15
  • 33

2 Answers2

2

Use BorderLayout with center attribute, if JLabel is the only component in the container (ie JPanel here) then if the BorderLayout is used, then its by default center. Its better you go with GroupLayout, developed by netbeans team in 2005.

eg:

class pan extends JPanel{

        JLabel label = new JLabel("Name");

        public void go(){

            this.setLayout(new BorderLayout());
            this.add(label,BorderLayout.CENTER);
        }
    }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

You can use the horizontal alignment also:

name.setHorizontalAlignment(SwingConstants.CENTER);
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
padman
  • 491
  • 1
  • 3
  • 14