Home >Java >javaTutorial >How to Center a JLabel Horizontally within a JPanel?

How to Center a JLabel Horizontally within a JPanel?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 10:14:16367browse

How to Center a JLabel Horizontally within a JPanel?

Centering a JLabel within a JPanel

When using a GUI builder to manage layout, it can be challenging to precisely align UI elements. This article provides detailed instructions on centering a JLabel horizontally within its parent JPanel, regardless of JPanel size changes.

Methods for Centering

There are several methods for centering a JLabel within a JPanel:

Border Layout:

JLabel label = new JLabel("Centered");
JPanel panel = new JPanel(new BorderLayout());
panel.add(label, BorderLayout.CENTER);

GridBagLayout:

JLabel label = new JLabel("Centered");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
panel.add(label, gbc);

GridLayout with Center Alignment:

JLabel label = new JLabel("Centered", SwingConstants.CENTER);
JPanel panel = new JPanel(new GridLayout());
panel.add(label);

BoxLayout (via @0verbose):

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(new JLabel("Centered"));
panel.add(Box.createHorizontalGlue());

These methods all align the JLabel horizontally within the JPanel, allowing it to remain centered even as the panel is resized.

The above is the detailed content of How to Center a JLabel Horizontally within a JPanel?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn