- 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 center a JLabel in a JPanel with GridBagLayout in Java?
Center a component in a JPanel with GridBagLayout. Let us first create a JFrame and JPanel inside it -
JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel();
Now, we will add our components −
JLabel label = new JLabel("Demo Label (Centered)"); label.setForeground(Color.white); JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");
Set the layout −
panel.setLayout(new GridBagLayout());
The following is an example to center a label in a panel with GridBagLayout −
Example
package my; import java.awt.Color; import java.awt.GridBagLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel(); JLabel label = new JLabel("Demo Label (Centered)"); label.setForeground(Color.white); JCheckBox checkBox = new JCheckBox("Checkbox (Centered)"); panel.setLayout(new GridBagLayout()); panel.add(label); panel.add(checkBox); panel.setBackground(Color.blue); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(600, 400); frame.setVisible(true); } }
Output
- Related Articles
- Java Program to center a JLabel in a JPanel with LayoutManager
- How to disable a JLabel in Java?
- How to disallow resizing component with GridBagLayout in Java
- How to create a JLabel with an image icon in Java?
- How to set location of JLabel in a JFrame with Java?
- How can I set a table in a JPanel in Java?
- How can we implement a scrollable JPanel in Java?
- Set the location of component in a GridBagLayout with Java
- How to center a Window in Java?
- Distribute extra horizontal and vertical space in a GridBagLayout with Java
- How can we set the background color to a JPanel in Java?
- How to add empty border to JPanel in Java?
- How can we rotate a JLabel text in Java?
- How to change text font for JLabel with HTML in Java?
- How to change JLabel font in Java

Advertisements