0

I have a subclass of JPanel that I'm trying to add labels to

for(int i = 0; i < 10; i++)
{
        JLabel lblPID = new JLabel("" + i);
        lblPID.setBounds(55, i * 50, 15, 15);
        this.add(lblPID);
}

But when this runs, the labels line up horizontally next to each other at the same y point, ignoring the bounds I'm setting. How do I have the panel lay them out vertically the way they're supposed to appear?

Chris
  • 7,270
  • 19
  • 66
  • 110
  • Which layout you used with `JPanel`? – Masudul Nov 30 '13 at 01:53
  • 2
    Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Nov 30 '13 at 01:56

1 Answers1

2

The likely problem is, the container you are adding your label to is using a layout manager, which is making it's own decisions about how your label should be laid out.

You should avoid using setBounds as you can not guarantee that the label will be rendered the same on different computers, even if they are running the same OS. Instead you should make use of appropriate layout managers, which make these decisions for you.

Take a look at Laying out Components within a Container for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366