BoxLayout 添加左边距

BoxLayout adding left margin

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

我的问题是大 lipsum 框左侧的边距,我该如何摆脱它?如果我不添加顶部组件,则没有边距。

这是我的代码,第二张图片是通过不添加 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);

这个 class 扩展 JPanel,并添加到一个 JFrame,这就是 pack()'d

虽然我不知道观察到的行为从何而来,但可以通过使用中间 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

My problem is the margin to the left of the large lipsum box, how can I get rid of this?

您需要使组件的对齐方式保持一致。即所有组件的对齐方式"X" 属性 应左对齐

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

descLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);

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