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

这将产生以下输出 −

更新于: 30-7 月-2019

420 次浏览

开启您的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.