Java grid bag layout: avoiding center alignment

In my GUI application, I have several JPanels that are created at different points while my program is running, and certain actions will cause one of them to appear in the scroll bar:

mViewport.setViewportView(currentPanel); 

The problem is that my panels are made using grid bag layouts, and the behavior of this is to concentrate inside the JScrollPane inside which it is located. This makes the GUI look weird.

Does anyone know how to force the bag layout panel in the upper left alignment?

Thanks!


EDIT

Note that here I am asking about the alignment of the entire panel in the scroll panel, and not about the components in the panel.

+4
source share
2 answers

I found a solution to my question after some attempts:

Setting the weights, apparently, can affect the alignment of the components in the JPanel for which the GridBagLayout used. However, this did not affect the alignment of the JPanel inside the JScrollPane .

I found a fairly simple solution that does not put the JPanel directly inside the JScrollPane , as I did with my earlier code:

 if (currentPanel != mCurrentPanel) { mViewport.setViewportView(currentPanel); } 

... but instead, to put the "external" JPanel inside the JScrollPane , and set this to use FlowLayout . Then, when I want to switch panels, I delete the old one and put the panel in "external". Panel.

 if (currentPanel != mCurrentPanel) { if (mCurrentPanel != null) { mOuterPanel.remove(mCurrentPanel); } mCurrentPanel = currentPanel; mOuterPanel.add(mCurrentPanel); } 

This approach worked pretty well, because it meant that I only had to make changes in one class, and not in each of the many panels that I had.

+6
source

You will need to set the weight (in GridBagConstraints ) on one or more components inside your panel. This leads to the fact that the "pressing" of the components takes up more free space (without weights, the components will occupy only what they need, and the panel will be concentrated in the available space).

If you want to align the components in the upper left corner of the scroll panel, set the lower weight of the y component to 1.0 and set the largest x weight of the component to 1.0.

+8
source

All Articles