MigLayout LC :: fill(),无需调整组件大小

时间:2014-04-20 23:08:53

标签: java swing miglayout

我有这段代码:

public static void main(String[] args) {
    JPanel panel1 = new JPanel(new MigLayout(new LC().fillX()));
    panel1.add(new JTextField("text1"), "span, grow");
    panel1.add(new JTextField("another text field"), "span, grow");
    panel1.add(new JTextField("text3"), "span, grow");

    JPanel panel2 = new JPanel(new MigLayout());
    JTextArea textArea = new JTextArea();
    textArea.setColumns(15);
    textArea.setRows(7);
    JScrollPane jsp = new JScrollPane(textArea);
    panel2.add(jsp, "span, grow");

    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(1, 2));
    frame.add(panel1);
    frame.add(panel2);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

产生这个:

enter image description here

但是,我试图让JTextFields均匀地分开。

所以,我改变了:

JPanel panel1 = new JPanel(new MigLayout(new LC().fillX()));

JPanel panel1 = new JPanel(new MigLayout(new LC().fill()));

(fill()与组合fillX()和fillY())相同,后者产生:

enter image description here

但是,我不希望JTextFields调整大小,只增加它们之间的差距。有没有办法用MigLayout完成这个?

1 个答案:

答案 0 :(得分:1)

我明白了。这是因为我为每个组件使用grow属性。要使用的正确属性是growx

public static void main(String[] args) {
    JPanel panel1 = new JPanel(new MigLayout(new LC().fill()));
    panel1.add(new JTextField("text1"), "span, growx");
    panel1.add(new JTextField("another text field"), "span, growx");
    panel1.add(new JTextField("text3"), "span, growx");

    JPanel panel2 = new JPanel(new MigLayout());
    JTextArea textArea = new JTextArea();
    textArea.setColumns(15);
    textArea.setRows(7);
    JScrollPane jsp = new JScrollPane(textArea);
    panel2.add(jsp, "span, grow");

    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(1, 2));
    frame.add(panel1);
    frame.add(panel2);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

enter image description here