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.
bguiz source share