Java GridBagConstraints

后端 未结 2 911
再見小時候
再見小時候 2021-01-26 16:50

I have 5 components in a JPanel. Everything is looking smooth with the first 4 component\'s I\'ve added. However, when I try adding a 5th component to the JPanel, the spacing be

2条回答
  •  误落风尘
    2021-01-26 17:10

    The reason that the last JLabel is not aligned with the previous 2 is that all labels are center aligned and appear in the same column. When there are only 2 labels, they appear aligned due to the happy coincidence that their FontMetric widths are equal. Add a third and the labels appear staggered.

    To fix, you can anchor the labels to counter this effect by anchoring the components to GridBagConstraints.WEST and set the weight along the x axis:

    gbc.weightx = 1;
    gbc.anchor = GridBagConstraints.WEST;
    

    This has the effect of left aligning component within their GridBagLayout "cells".

提交回复
热议问题