- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 use GridBagConstraints to layout two components in the same line with Java
To align two components in the same line, you need to set the contrainsts of the GridBagConstraints properly. Let’s say we have two components in panel1. Set the contraints using Insets as well −
panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
The following is an example to set two components in the same line −
Example
package my; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setSize(550, 300); JPanel panel1 = new JPanel(new GridBagLayout()); JCheckBox checkBox1 = new JCheckBox("Undergraduate"); JCheckBox checkBox2 = new JCheckBox("Graduate"); panel1.add(checkBox1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0, 0, 0), 0, 0)); panel1.add(checkBox2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0, 0, 0), 0, 0)); frame.add(panel1); frame.setVisible(true); } }
Output
- Related Articles
- How to use Constraint Layout with recyclerview?
- How to use appbar layout in android?
- How to use Android sequence layout?
- How to work with border layout position options in Java?
- How to create two line charts in the same plot in R?
- How to deal with reusable components in Selenium Java?
- How to capture multiple matches in the same line in Java regex
- How to create a Box Layout in Java?
- How to add components with a Relative X Position in Java
- How to add components with a relative Y position in Java?
- What is the importance of the GridBagConstraints class in Java?
- How to left align components vertically using BoxLayout with Java?
- How to create an invisible fixed width component between two components in Java?
- How to create an invisible fixed height component between two components in Java?
- How to add components with relative X and Y Coordinates in Java?

Advertisements