Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to left align components vertically using BoxLayout with Java?
To align components vertically, use the BoxLayout −
JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
Now, create a Panel and add some buttons to it. After that set left alignment of components which are already arranged vertically using Component.LEFT_ALIGNMENT constant −
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
The following is an example to left align components vertically with BoxLayout −
Example
package my;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(100, 500));
panel.setMaximumSize(new Dimension(100, 500));
panel.setBorder(BorderFactory.createTitledBorder("demo"));
frame.getContentPane().add(panel);
frame.setSize(550, 300);
frame.setVisible(true);
}
}
Output

Advertisements