- 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 the location of component in a GridBagLayout with Java
To set the location of component, use the GridBagConstraints. Here, we have two components −
GridBagConstraints gbc = new GridBagConstraints(); JLabel label = new JLabel("Email-Id − "); JTextArea text = new JTextArea(); text.setText("Add id here...");
Set the location with gridx and gridy −
gbc.gridx = 0; gbc.gridy = 0; layout.setConstraints(label, gbc); panel.add(label);
The following is an example to set the location of component in a GridBagLayout −
Example
package my; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel(); GridBagLayout layout = new GridBagLayout(); panel.setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); JLabel label = new JLabel("Email-Id − "); JTextArea text = new JTextArea(); text.setText("Add id here..."); gbc.gridx = 0; gbc.gridy = 0; layout.setConstraints(label, gbc); panel.add(label); gbc.gridx = 1; gbc.gridy = 1; layout.setConstraints(text, gbc); panel.add(text); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } }
Output
- Related Articles
- Set a component and place it next to the previously added component with GridBagLayout in 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?
- How to set location of JLabel in a JFrame with Java?
- How to center a JLabel in a JPanel with GridBagLayout in Java?
- Distribute extra horizontal and vertical space in a GridBagLayout with Java
- How to set columnWeights and rowWeights in a GridBagLayout?
- How to set vertical alignment for a component in Java?
- How to set the location of the Tabs in a JTabbedPane Container to the left in Java?
- How to set the location of a button anywhere in JFrame?
- Java Program to create a layout using GridBagLayout
- Get the path of the file selected in the JFileChooser component with Java
- How to limit the values in a Number JSpinner Component with Java?
- How to find a node in a JTree Component with Java?
- What are the differences between GridLayout and GridBagLayout in Java?

Advertisements