1

我有一个 JPanel ( panel),其布局设置为 BoxLayout。我还有一个自定义类MapRow,它扩展了 JPanel(并在其中包含一些简单的 FlowLayout 组件),我希望以简单的左对齐自上而下的方式添加MapRowto的实例。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我刚刚用 dummy s替换了实例JButton,它们左对齐都很好。所以像JButtons 这样的组件可以使用 左对齐setAlignmentX(),但是 JPanels 不能?

4

1 回答 1

1

You should use a LEFT-alignement for you FlowLayout in MapRow. Here is a small SSCCE illustrating that:

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();
            }
        });
    }
}
于 2012-07-31T08:31:02.563 回答