我创建了一个Box
,其中包含JLabel
,以及一个JScrollPane
和JTextArea
。但是,JLabel
的左侧总是有一些空间:
完整的演示代码:
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.")));
}
}
使用setBorder(BorderFactory.createEmptyBorder(int顶部,int左侧,int底部,int右侧);参考:https://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html
How to Use BoxLayout (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)X对齐不仅影响组件之间的相对位置,还影响组件(作为一个组)在其容器中的位置。
因此,不仅对于setAlignmentX(Component.LEFT_ALIGNMENT)
,而且对于JLabel
,都需要JScrollPane
。
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);
}
}