Syntax error How to create Glue to fill the space between neighbouring components in Java?

How to create Glue to fill the space between neighbouring components in Java?



Let’s say we have 6 components and we need to fill the space between some of them −

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

To fill the space and separate components, create a Glue using the createGlue() method −

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

The following is an example to fill the space between neighbouring components −

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("Matches");
      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");
      Box box = new Box(BoxLayout.X_AXIS);
      box.add(button1);
      box.add(button2);
      box.add(Box.createGlue());
      box.add(button3);
      box.add(button4);
      box.add(Box.createGlue());
      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);
   }
}

Output


Updated on: 2019-07-30T22:30:26+05:30

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements