BoxLayout添加左边距

时间:2017-01-03 13:42:16

标签: java swing jlabel layout-manager boxlayout

我有一个有BoxLayout(Page轴)的JPanel,我想布置两个组件,一个在另一个之上。

enter image description here

我的问题是大嘴唇盒左边的边缘,我怎么能摆脱这个?如果我不添加顶部组件,则没有余量。

enter image description here

这是我的代码,第二张图片是通过不添加headerPanel

创建的
JLabel commandLabel = new JLabel(command);
    JLabel paramLabel = new JLabel(params);
    JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
    Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;

    commandFont = baseFont.deriveFont(Font.BOLD);
    paramFont = baseFont.deriveFont(Font.ITALIC);
    descFont = baseFont.deriveFont(Font.PLAIN);

    commandLabel.setFont(commandFont);
    paramLabel.setFont(paramFont);
    descLabel.setFont(descFont);
    descLabel.setAlignmentX(LEFT_ALIGNMENT);
    descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));   
    JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
        headerPanel.add(commandLabel);
        headerPanel.add(paramLabel);
    this.add(headerPanel);
    this.add(descLabel);

此课程扩展JPanel,并添加到JFrame,这只是pack()'d

2 个答案:

答案 0 :(得分:1)

虽然我无法分辨观察到的行为来自哪里,但是可以通过使用中间JPanel来包含您的标签来实现预期的显示,而不是直接添加JLabel

    JLabel commandLabel = new JLabel(command);
    JLabel paramLabel = new JLabel(params);
    JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
    Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;

    commandFont = baseFont.deriveFont(Font.BOLD);
    paramFont = baseFont.deriveFont(Font.ITALIC);
    descFont = baseFont.deriveFont(Font.PLAIN);

    commandLabel.setFont(commandFont);
    paramLabel.setFont(paramFont);
    descLabel.setFont(descFont);
    descLabel.setAlignmentX(LEFT_ALIGNMENT);
    descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));   
    JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
    JPanel descPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));// added
    headerPanel.add(commandLabel);
    headerPanel.add(paramLabel);

    descPanel.add(descLabel);// added

    this.add(headerPanel);
    this.add(descPanel);// modified

答案 1 :(得分:1)

  

我的问题是大嘴唇盒左边的边缘,我怎么能摆脱这个呢?

您需要使组件的对齐保持一致。那是对齐&#34; X&#34;所有组件的属性应保持对齐。

我猜测JLabel是居中对齐的,所以你需要使用:

descLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);

有关更多信息和示例,请参阅How to Use BoxLayout上Swing教程中的Fixing Alignment Problems部分。