[英]How to make BoxLayout left-align properly?
I created a Box
which contains a JLabel
, and a JScrollPane
with a JTextArea
.我创建了一个包含
JLabel
的Box
和一个带有JTextArea
的JScrollPane
。 However there is always some space on left side of JLabel
:但是
JLabel
的左侧总是有一些空间:
Full demonstration code:完整的演示代码:
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)
如何使用 BoxLayout(Java™ 教程 > 使用 JFC/Swing 创建 GUI > 在容器中布置组件)
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.X 对齐不仅影响组件相对于彼此的位置,还影响组件(作为一个组)在其容器中的位置。
For this reason, it is necessary to setAlignmentX(Component.LEFT_ALIGNMENT)
not only for JLabel
but also for JScrollPane
.出于这个原因,不仅要为
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);
}
}
use setBorder(BorderFactory.createEmptyBorder(int top, int left, int bottom, int right); ref: https://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html use setBorder(BorderFactory.createEmptyBorder(int top, int left, int bottom, int right); ref: https://docs.oracle.com/javase/7/docs/api/javax/swing/BorderFactory.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.