如何在 Java 中在两个组件之间创建不可见的固定高度组件?

java 8object oriented programmingprogramming

使用 createVerticalStrut() 方法在两个组件之间创建不可见的固定高度组件。假设我们有一些按钮,我们正在它们之间创建一个固定高度 −

box.add(button4);
box.add(Box.createVerticalStrut(50));
box.add(button5);
box.add(Box.createVerticalStrut(30));
box.add(button6);

以下是在 Java 中在两个组件之间创建不可见的固定高度组件的示例 −

示例

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.Y_AXIS);
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(Box.createVerticalStrut(50));
      box.add(button5);
      box.add(Box.createVerticalStrut(30));
      box.add(button6);
      box.add(button7);
      box.add(button8);
      JScrollPane jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(box);
      frame.add(jScrollPane, BorderLayout.CENTER);
      frame.setSize(550, 350);
      frame.setVisible(true);
   }
}

上面,我们已将固定高度(以像素为单位)设置为在 createVerticalStrut() 方法的参数下可见。

输出


相关文章