如何在 Java 中建立盒子以從左向右顯示元件
Box 是重量級容器,它使用 BoxLayout 物件作為其佈局管理器。要從左到右顯示元件,請使用 Box createHorizontalBox() 方法。
我們首先建立一些按鈕元件 −
JButton button1 = new JButton("One");
JButton button2 = new JButton("Two");
JButton button3 = new JButton("Three");
JButton button4 = new JButton("Four");
JButton button5 = new JButton("Five");
JButton button6 = new JButton("Six");現在,建立一個 Box 並從左到右對齊所有按鈕 −
Box box = Box.createHorizontalBox(); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(button5); box.add(button6);
以下是建立 Box 以從左到右顯示元件的示例 −
示例
package my;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("One");
JButton button2 = new JButton("Two");
JButton button3 = new JButton("Three");
JButton button4 = new JButton("Four");
JButton button5 = new JButton("Five");
JButton button6 = new JButton("Six");
Box box = Box.createHorizontalBox();
box.add(button1);
box.add(button2);
box.add(button3);
box.add(button4);
box.add(button5);
box.add(button6);
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setViewportView(box);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(550, 250);
frame.setVisible(true);
}
}這將產生以下輸出 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP