java - 如何使 BoxLayout 正确左对齐?

标签 java swing layout-manager boxlayout

我创建了一个 Box,其中包含一个 JLabel 和一个带有 JTextAreaJScrollPane。然而,JLabel 左侧始终有一些空格:

Jlabel not fully left-aligned

完整演示代码:

import java.awt.*;
import javax.swing.*;

public class BoxAlignmentTest extends JFrame {

    public static void main(String[] args) {
        BoxAlignmentTest test = new BoxAlignmentTest();
        test.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        test.setSize(500, 200);
        test.setVisible(true);
    }

    public BoxAlignmentTest() throws HeadlessException {
        Box box = Box.createVerticalBox();
        setContentPane(box);

        JLabel label = new JLabel("This label isn't fully left-aligned.");
        label.setOpaque(true);
        label.setBackground(Color.orange);
        label.setAlignmentX(Component.LEFT_ALIGNMENT);  // Set left alignment

        box.add(label);
        box.add(new JScrollPane(new JTextArea("This is a text area.")));
    }
}

最佳答案

How to Use BoxLayout (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)
The X alignments affect not only the components' positions relative to each other, but also the location of the components (as a group) within their container.

因此,不仅对于 JLabel,而且对于 JScrollPane 都需要 setAlignmentX(Component.LEFT_ALIGNMENT)

import java.awt.*;
import javax.swing.*;

public class BoxAlignmentTest2 extends JFrame {
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      BoxAlignmentTest2 test = new BoxAlignmentTest2();
      test.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      test.setSize(500, 200);
      test.setVisible(true);
    });
  }

  public BoxAlignmentTest2() throws HeadlessException {
    JLabel label = new JLabel("This label isn't fully left-aligned.");
    label.setOpaque(true);
    label.setBackground(Color.orange);
    label.setAlignmentX(Component.LEFT_ALIGNMENT); // Set left alignment

    JScrollPane scroll = new JScrollPane(new JTextArea("This is a text area."));
    scroll.setAlignmentX(Component.LEFT_ALIGNMENT); // <- add

    Box box = Box.createVerticalBox();
    box.add(label);
    box.add(scroll);

    add(box); // = getContentPane().add(box, BorderLayout.CENTER);
  }
}

关于java - 如何使 BoxLayout 正确左对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725399/

相关文章:

java - ColdFusion 将枚举传递给 Java 方法

java BoxLayout面板的对齐方式

java - 将多个小面板添加到框架中

java - 网格中具有固定大小的组件

Java Android LiveData 调用依赖于其他 LiveData 的 Room 查询

java - 找到树中节点深度的更好方法

java - 你如何检测鼠标光标是否在 java 中的 JFrame 内?

java - 我如何将 JPanel 分成 70% 30%

javax.faces.view.facelets.TagAttributeException : Invalid path

java - Jbutton 在两种背景颜色之间闪烁