如何使用 BoxLayout 利用 Java 将组件垂直左对齐?
若要垂直对齐组件,请使用 BoxLayout −
JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
现在,创建一个面板,并添加一些按钮。之后,使用 Component.LEFT_ALIGNMENT 常量设置已垂直排列的组件的左对齐 −
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);以下是使用 BoxLayout 垂直左对齐组件的示例 −
示例
package my;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(100, 500));
panel.setMaximumSize(new Dimension(100, 500));
panel.setBorder(BorderFactory.createTitledBorder("demo"));
frame.getContentPane().add(panel);
frame.setSize(550, 300);
frame.setVisible(true);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP