Centering a JLabel on a JPanel

34,774

Solution 1

By using Borderlayout, you can put any of JComponents to the CENTER area. For an example, see an answer to Stack Overflow question Get rid of the gap between JPanels. This should work.

Solution 2

Here are four ways to center a component:

4 Centered Components

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class CenterComponent {

    public static JLabel getLabel(String text) {
        return getLabel(text, SwingConstants.LEFT);
    }

    public static JLabel getLabel(String text, int alignment) {
        JLabel l = new JLabel(text, alignment);
        l.setBorder(new LineBorder(Color.RED, 2));
        return l;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JPanel p = new JPanel(new GridLayout(2,2,4,4));
                p.setBackground(Color.black);
                p.setBorder(new EmptyBorder(4,4,4,4));

                JPanel border = new JPanel(new BorderLayout());
                border.add(getLabel(
                    "Border", SwingConstants.CENTER), BorderLayout.CENTER);
                p.add(border);

                JPanel gridbag = new JPanel(new GridBagLayout());
                gridbag.add(getLabel("GridBag"));
                p.add(gridbag);

                JPanel grid = new JPanel(new GridLayout());
                grid.add(getLabel("Grid", SwingConstants.CENTER));
                p.add(grid);

                // from @0verbose
                JPanel box = new JPanel();
                box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));

                box.add(Box.createHorizontalGlue());
                box.add(getLabel("Box"));
                box.add(Box.createHorizontalGlue());
                p.add(box);

                JFrame f = new JFrame("Streeeetch me..");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setContentPane(p);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        });
    }
}

Solution 3

Even with BoxLayout you can achieve that:

JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS ));

JLabel label = new JLabel();
listPane.add(Box.createHorizontalGlue());
listPane.add(label);
listPane.add(Box.createHorizontalGlue());

mKorbel's solution is perfect for your goal. Anyway I always like to suggest BoxLayout because it's very flexible.

Solution 4

Mara: "thanks for your response, however the NetBeans GUI Build uses GroupLayout and this is not overridable."

Not true! Right click anywhere inside JFrame (or any other GUI container) in NetBeans GUI builder and select "Set Layout". By default is selected "Free Design", which is Group layout, but you can select any other layout including Border layout as advised by mKorbel.

Solution 5

There's many ways to do this, depending on the layout manager(s) you use. I suggest you read the Laying Out Components Within a Container tutorial.

I believe the following will work, regardless of layout manager:

JLabel.setHorizontalAlignment(SwingConstants.CENTER)

Share:
34,774
IAmYourFaja
Author by

IAmYourFaja

my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.

Updated on September 04, 2020

Comments

  • IAmYourFaja
    IAmYourFaja over 3 years

    I'm using the NetBeans GUI builder to handle my layout (I'm terrible with LayoutManagers) and am trying to place a simple JLabel so that it is always centered (horizontally) inside its parent JPanel. Ideally, this would maintain true even if the JPanel was resized, but if that's a crazy amount of coding than it is sufficient to just be centered when the JPanel is first created.

    I'm bad enough trying to handle layouts myself, but since the NetBeans GUI Builder autogenerates immutable code, it's been impossible for me to figure out how to do this centering, and I haven't been able to find anything online to help me.

    Thanks to anybody who can steer me in the right direction!

  • IAmYourFaja
    IAmYourFaja over 12 years
    thanks for your response, however the NetBeans GUI Build uses GroupLayout and this is not overridable. Remember I'm not just trying to fight Swing and its menacing LayoutManagers, I'm fighting a GUI Builder that autogenerates code specifically for GroupLayout!
  • Heisenbug
    Heisenbug over 12 years
    @Mara: i really suggest you to start learn how to use layout manager. It's not so difficult.Instead It's difficult to achieve the same results using gui builder .
  • IAmYourFaja
    IAmYourFaja over 12 years
    Thanks Overbose, but I'm stuck with GroupLayout. And if I spend too much more time on the client-side I will definitely take up your suggestion and learn the LayoutManagers from the ground on up. I'm just looking for a quick and dirty solution. That uses GroupLayout.
  • ChadNC
    ChadNC over 12 years
    I've never been a fan of gui builders in any Java IDE but I can understand why people use them. I usually just use a combination layout managers to reach the desired look. However, from your description of what you want I would say just use the border layout as described.
  • Andrew Thompson
    Andrew Thompson over 12 years
    "I'm stuck with GroupLayout" Only because you don't know how to use Netbeans. I don't use it, but I've seen code from Netbeans users (even when using the GUI designer) that used all the standard layouts.
  • trashgod
    trashgod over 12 years
    "NetBeans GUI Builder uses GroupLayout," but you can select another from the inspector.