Search code examples
javaswingjframejpanelgridbaglayout

How to make a dynamic JPanel stick to the top?


I'm using GridBagLayout and JPanel 2 seems to always be in the center of the JPanel 1. JPanel 2 gets dinamically adjusted in height throughout the program, so I can't stick it to the top using gbc.insets.top = -15; (gbc = GridBagConstraints) for example. I've tried gbc.anchor = GridBagConstraints.PAGE_START; or gbc.gridheight = 3; but they don't seem to do what I'm looking for.

Assuming JPanel 1 and JFrame stay the same size, (JFrame isn't resizable), how can I make JPanel 2 be all the way at the top, without that gap?

enter image description here


Solution

  • JPanel 2 seems to always be in the center of the JPanel

    Then it would seem you are adding panel1 to panel2, since the default behaviour for the GridBagLayout is to center the component relative to its parent.

    Based on the picture shown just use the BorderLayout on the frame (which is the default). Then you would:

    1. add panel2 to the BorderLayout.LINE_START
    2. add panel1 to the BorderLayout.CENTER

    Read the section from the Swing tutorial on How to Use BorderLayout for more information.