如何使用BoxLayout和Java使元件居中對齊?
我們先建立一個面板並設定一些按鈕 −
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);現在,使用 setAlignmentX() 並在其中指定對齊到元件的中心 −
panel.setAlignmentX(Component.CENTER_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.CENTER_ALIGNMENT);
panel.setPreferredSize(new Dimension(400, 100));
panel.setMaximumSize(new Dimension(400, 100));
panel.setBorder(BorderFactory.createTitledBorder("demo"));
frame.getContentPane().add(panel);
frame.setSize(550, 300);
frame.setVisible(true);
}
}輸出

廣告
資料結構
網路
資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP