- 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
Java Program to center a JLabel in a JPanel with LayoutManager
Here, we are using the LayoutManager GridBagLayout to center the components. We have two components here including a label and we have set the layout as GridBagLayout −
JLabel label = new JLabel("Name (Centered Label): "); JTextArea text = new JTextArea(); text.setText("Add name here..."); panel.setLayout(new GridBagLayout());
The following is an example to center a JLabel in a JPanel with LayoutManager −
Example
package my; import java.awt.GridBagLayout; import javax.swing.BorderFactory; 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(); JLabel label = new JLabel("Name (Centered Label): "); JTextArea text = new JTextArea(); text.setText("Add name here..."); panel.setLayout(new GridBagLayout()); panel.add(label); panel.add(text); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(500, 300); frame.setVisible(true); } }
Output
- Related Articles
- How to center a JLabel in a JPanel with GridBagLayout in Java?
- What is a LayoutManager and types of LayoutManager in Java?\n
- How to set location of JLabel in a JFrame with Java?
- How to create a JLabel with an image icon in Java?
- How to disable a JLabel in Java?
- Java Program to set alignment for text in JLabel
- How can we implement a scrollable JPanel in Java?
- How can I set a table in a JPanel in Java?
- Java Program to change JLabel text after creation
- How can we set the background color to a JPanel in Java?
- How to add empty border to JPanel in Java?
- How to center a Window in Java?
- How to change text font for JLabel with HTML in Java?
- How can we rotate a JLabel text in Java?
- How can we implement a JLabel text with different color and font in Java?

Advertisements