- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 set vertical alignment for a component in Java?
For vertical alignment, create a frame and set the layout using the BoxLayout manager −
JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
Above, we have set the BoxLayout to set the alignment since it is a layout manager that allows multiple components to be laid out either vertically or horizontally. We have set vertical alignment here −
BoxLayout.X_AXIS
The following is an example to set vertical alignment for a component −
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("Clear"); JButton btn2 = new JButton("Reset"); JButton btn3 = new JButton("Submit"); panel.add(btn1); panel.add(btn2); panel.add(btn3); 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
- Related Articles
- Java Program to set alignment for text in JLabel
- How to set the vertical alignment of the content in an element with JavaScript?
- How to set Text alignment in HTML?
- How to set Heading alignment in HTML?
- Java Program to set Horizontal Alignment of content in a JTextField
- How to create Titled Border for a component in Java?
- How to create a compound border for a component in Java?
- CSS Central, Horizontal and Vertical Alignment
- How to set vertical gap between elements in a GridLayout with Java?
- How to create two borders for a single component in Java?
- Set a component and place it next to the previously added component with GridBagLayout in Java
- Vertical alignment of an image using CSS
- How can I set an EtchedBorder from BorderFactory class to a component in Java?
- How to set alignment to text in text flow layout?
- Horizontal and Vertical Center Alignment with Flexbox in CSS3

Advertisements