如何使用 Java 创建盒子布局?


要在 Java Swing 中创建盒子布局,请使用 BoxLayout 类。我们还指定了组件应按从左向右或从上到下排列 -

Box box = new Box(BoxLayout.X_AXIS);
box.add(button1);
box.add(button2);
box.add(button3);
box.add(button4);
box.add(Box.createGlue());
box.add(button5);
box.add(button6);
box.add(button7);
box.add(button8);

上面这个盒子布局中一共有 8 个按钮。我们使用 createGlue() 方法隔开了其中 4 个按钮。

以下是 Java 中创建 BoxLayout 的示例:

示例

package my;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
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("Groups");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton button1 = new JButton("CSK");
      JButton button2 = new JButton("DC");
      JButton button3 = new JButton("MI");
      JButton button4 = new JButton("SRH");
      JButton button5 = new JButton("RR");
      JButton button6 = new JButton("KKR");
      JButton button7 = new JButton("KXIP");
      JButton button8 = new JButton("RCB");
      Box box = new Box(BoxLayout.X_AXIS);
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(Box.createGlue());
      box.add(button5);
      box.add(button6);
      box.add(button7);
      box.add(button8);
      JScrollPane jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(box);
      frame.add(jScrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

输出

更新时间: 2019-07-30

2000+ 次浏览

开启你的 职业生涯

完成课程取得认证

开始
广告
© . All rights reserved.