How to create an invisible fixed height component between two components in Java?

Java 8Object Oriented ProgrammingProgramming

Use the createVerticalStrut() method to create an invisible fixed height component between two components. Let’s say we have some button and we are creating a fixed height between them −

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

The following is an example to create an invisible fixed height component between two components in Java −

Example

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);
   }
}

Above, we have set the fixed height in pixels as visible under parameter of the createVerticalStrut() method.

Output

raja
Published on 04-Jun-2019 11:41:51
Advertisements