Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to create a Box to display components from left to right in Java
Box is lightweight container that uses a BoxLayout object as its layout manager. To display components from left to right, use Box createHorizontalBox() method.
Let us first create some button components −
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");
Now, crate a Box and align all the buttons from left to right −
Box box = Box.createHorizontalBox(); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(button5); box.add(button6);
The following is an example to create a Box to display components from left to right −
Example
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);
}
}
This will produce the following output −

Advertisements
