我应该如何使用GridBagLayout让JComponents像FlowLayout.Left一样对齐

时间:2015-10-29 13:59:39

标签: java swing alignment gridbaglayout

我正在使用GridBagLayout,我希望我的组件从左到右排列,就像FlowLayout FlowLayout.LEFT一样。 下图解释了我的内容(左侧),以及我的目标。 (在右边)

MiMage

这是我为此目的编写的一些代码。已经使用注释行,同时(不合理地)找出解决方案:

public class Main {
    public static void main(String[] args)  {   
        SwingUtilities.invokeLater(new Demo());     
    }
}

class Demo implements Runnable{
    @Override
    public void run() {
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(250,100));

        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
        panel.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(0,10,0,0);
        gbc.anchor = GridBagConstraints.EAST;
        JLabel label1 = new JLabel("MyLabel1"); 
//      JLabel label1 = new JLabel("MyLabel1",SwingConstants.LEFT); 
//      label1.setHorizontalAlignment(SwingConstants.LEFT);
//      gbc.fill=GridBagConstraints.HORIZONTAL;
//      gbc.ipadx = 60;
//      gbc.ipady = 10;
        panel.add(label1,gbc);

        JLabel label2 = new JLabel("MyLabel2"); 
        panel.add(label2,gbc);

        frame.add(panel);
        frame.setVisible(true);
    }

}

1 个答案:

答案 0 :(得分:0)

Thanks to user camickr i found that:

anchor attribute of GridBagConstraints

Used when the component is smaller than its display area to determine where (within the area) to place the component.

and this is properly set to:

 gbc.anchor = GridBagConstraints.WEST;

but it is not enough, since:

weightx and weighty attribute of GridBagConstraints

Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing behavior. Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container.

give it a value between 0.1 and 1 before adding JComponent and it will works:

   gbc.weightx = 0.1; //0.1 works well in my case since frame can't be resized

Thanks everyone.