- 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
Set a component and place it next to the previously added component with GridBagLayout in Java
We have set a component first −
GridBagConstraints constraints = new GridBagConstraints(); constraints.gridy = 0; panel.add(new JButton("First row"), constraints);
Now, we will place it next to the previously added component −
constraints.gridx = GridBagConstraints.RELATIVE; constraints.gridy = 1; panel.add(new JButton("2nd row 1st column"), constraints); panel.add(new JButton("2nd row 2nd column"), constraints);
Example
package my; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; 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); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridy = 0; panel.add(new JButton("First row"), constraints); constraints.gridx = GridBagConstraints.RELATIVE; constraints.gridy = 1; panel.add(new JButton("2nd row 1st column"), constraints); panel.add(new JButton("2nd row 2nd column"), constraints); frame.add(panel); frame.setSize(550, 300); frame.setVisible(true); } }
Output
- Related Articles
- Set the location of component in a GridBagLayout with Java
- How to disallow resizing component with GridBagLayout in Java
- How to position component at the top of the grid cell with GridBagLayout in Java?
- Java Program to place component in bottom-right corner with BorderLayout
- Java program to insert a component into a JTextPane component
- How to set vertical alignment for a component in Java?
- How to find a node in a JTree Component with Java?
- How to limit the values in a Number JSpinner Component with Java?
- How to create a JMenuBar Component in Java?
- Inserting an Image into a JTextPane Component with Java
- How to center align component using BoxLayout with Java?
- How can I set an EtchedBorder from BorderFactory class to a component in Java?
- How to add a tooltip to a component in Java?
- How to get the leaf after this node in a JTree component with Java?
- What is a View component and how to use it in React Native?

Advertisements