java - BoxLayout 添加左边距

标签 java swing jlabel layout-manager boxlayout

我有一个带有 BoxLayout (页面轴)的 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()

最佳答案

虽然我无法判断观察到的行为来自何处,但可以通过使用中间 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

关于java - BoxLayout 添加左边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41444875/

相关文章:

java - 为什么下面的表达式返回 true?

java - actionPerformed 时出现 NullPointerException。不知道为什么

java - 使 JLabel 适合其父 JPanel 或为其指定最小尺寸

java - 使用 Lucene 索引单个 Xml 文件

java - 无法正确将 Base64 MIME 图像解码为字节数组 (Java)

java - Eclipse 的最佳 GUI 设计器?

java - 我们如何更改标签中的行?

java - 如何通过java中的mouselisteners获取2D数组(jlabel)的索引?

java - 当元素重新排序时,使用 XMLunit 进行 XML 比较不起作用

java - 有没有更简单的方法来显示这个 Java UI?