Search code examples
javapositioningjpaneljcomponent

Auto positioning components in a JPanel in Java


I'm adding some JCheckBox components to a JPanel at runtime.
My problem is that all these components are added on the same place.
So they are displaying on each other.
Is there any way to set them for auto positioning?
I mean they find a place next to previous component in JPanel and I get rid of manual positioning them.

Thanks


Solution

  • The short answer is use a LayoutManager. But, LayoutManager work very differently depending on what you need. So you'll need to know how you want your dynamic checkboxes to layout. Where in your UI will be the expandable part to absorb potentially N number of checkboxes. Without knowing how you want to visually layout components you I can't really advise you which layout manager is best for your situation.

    General advise about LayoutManagers is TableLayout is very good a dynamic components. It's very straight forward, and still very powerful. Better behaved and much much less code needed than say GridBagLayout, and simpler to understand than say SpringLayout or MigLayout. Get it, learn how to use it, then really ask yourself.

    Do I truly need to dynamically build my UI of checkboxes or can I accomplish this with a set of simple panels in a CardLayout and switch between them based on some input (this is much much simpler than dynamic layout of controls at runtime).

    http://java.net/projects/tablelayout

    JPanel panel = new JPanel( new TableLayout(...) ); // sets the LayoutManager used by JPanel
    panel.add( new JCheckBox(), "1 2" ); // add to row 1 column 2
    

    You get the picture.