使用BoxLayout水平对齐两个JLabel

时间:2014-03-24 16:05:35

标签: java swing layout jlabel boxlayout

我只想使用BoxLayout水平对齐两个JLabel,这可能吗?这是我的代码:

public class CreditsPanel extends JPanel {

private static final long serialVersionUID = 1L;
private static final int GAP = 75;

public CreditsPanel() {
    super();

    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    JLabel title = new JLabel("The developers of the game: ");
    this.add(title);
    title.setAlignmentX(Component.CENTER_ALIGNMENT);
    this.add(Box.createVerticalStrut(GAP));

    JLabel[] names = new JLabel[2];
    names[0] = new JLabel("Pippo");
    names[1] = new JLabel("Pluto");
    int i = 0;
    for (JLabel l : names) {
        ImageIcon icon = getIcon(i);
        l.setAlignmentX(Component.CENTER_ALIGNMENT);
        l.setHorizontalTextPosition(JLabel.CENTER);
        l.setVerticalTextPosition(JLabel.TOP);
        l.setIcon(icon);
        this.add(l, BorderLayout.EAST);
        this.add(Box.createVerticalStrut(25));
        i++;
    }
}

提前谢谢你。 getIcon只是一个私有方法,可以将不同的图标设置为我的标签。

现在我有这样的事情: http://postimg.org/image/tml9wmr4f/ 我想要这个: http://postimg.org/image/nlg0fvygf/

1 个答案:

答案 0 :(得分:1)

基本代码对我来说很好。

唯一与众不同的是:

this.add(l, BorderLayout.EAST);

不知道BorderLayoutEAST是否会导致问题。

如果您需要更多帮助,请发布SSCCE