如何使用 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);
   }
}

輸出


更新於:30-7 月-2019

2K+次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.