我有一个JPanel(panel
),其布局设置为BoxLayout。我还有一个自定义类MapRow
,它扩展了JPanel(在一个简单的FlowLayout中有一些组件),我希望将MapRow
的实例添加到panel
中简单,左对齐,自上而下的时尚。请考虑以下方法:
public void drawMappingsPanel(JPanel panel) {
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
int s = /* aMethodCall() */;
for (int i = 0; i < s; i++) {
MapRow row = new MapRow();
row.setAlignmentX(LEFT_ALIGNMENT);
panel.add(row);
}
}
但是,当我运行代码时,所有MapRow
面板都集中对齐,如下所示:
如何将MapRow
面板对齐到左侧? setAlignmentX(LEFT_ALIGNMENT)
方法似乎不起作用......
编辑:我刚刚将MapRow
的实例替换为虚拟JButton
s,并且它们左对齐全部正常。因此JButton
s之类的组件可以使用setAlignmentX()
左对齐,但JPanel不能?
答案 0 :(得分:1)
您应该在MapRow中为FlowLayout使用LEFT-alignment。这是一个小SSCCE,说明了:
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestJPanels {
protected void initUI() {
final JFrame frame = new JFrame(TestJPanels.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel("Label-" + i);
label.setBorder(BorderFactory.createLineBorder(Color.GREEN));
JPanel insidePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
insidePanel.add(label);
insidePanel.setBorder(BorderFactory.createLineBorder(Color.RED));
panel.add(insidePanel);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestJPanels().initUI();
}
});
}
}