我有一個包含子面板的BoxLayout管理器的JPanel。我希望這些子面板內的組件具有左對齊,但它們總是顯示居中。 它看起來像BoxLayout正確地對齊直接插入的組件,但是當它們位於子面板內時,則無法做到這一點。BoxLayout忽略子面板對齊
我已經修改http://www.java2s.com/Tutorial/Java/0240__Swing/YAxisAlignment.htm發現這個例子,每個按鈕被放置在子面板內,然後將子面板被放置在BoxLayout的經理主面板中:
public class YAxisAlignX {
private static Container makeIt(String title, float alignment) {
String labels[] = { "--", "----", "--------", "------------" };
JPanel container = new JPanel();
container.setBorder(BorderFactory.createTitledBorder(title));
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
// modified loop. the original version does not create JPanel pan.
// adds the buttons directly the the JPanel container with the
// BoxLayout
for (int i = 0, n = labels.length; i < n; i++) {
JPanel pan = new JPanel();
JButton button = new JButton(labels[i]);
pan.add(button);
button.setAlignmentX(alignment);
pan.setAlignmentX(alignment);
container.add(pan);
}
return container;
}
public static void main(String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel1 = makeIt("Left", Component.LEFT_ALIGNMENT);
Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
Container panel3 = makeIt("Right", Component.RIGHT_ALIGNMENT);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
如果執行此版本中,您可以看到按鈕都居中,儘管設置了對齊。這是爲什麼發生?有沒有解決方法?就我而言,每個子面板都包含多個組件,我不想直接添加到主面板。
非常感謝。
謝謝您的明確解釋! – karmapolice