Centering a JLabel in a JPanel

送分小仙女□ 提交于 2019-11-27 21:18:20

Set GridBagLayout for JPanel, put JLabel without any GridBagConstraints to the JPanel, JLabel will be centered

example

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

public class CenteredJLabel {

    private JFrame frame = new JFrame("Test");
    private JPanel panel = new JPanel();
    private JLabel label = new JLabel("CenteredJLabel");

    public CenteredJLabel() {
        panel.setLayout(new GridBagLayout());
        panel.add(label);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                CenteredJLabel centeredJLabel = new CenteredJLabel();
            }
        });
    }
}

Supose your JLabel is called label, then use:

label.setHorizontalAlignment(JLabel.CENTER);

BoxLayout is the way to go. If you set up a X_AXIS BoxLayout, try adding horizontal glues before and after the component:

panel.add(Box.createHorizontalGlue());
panel.add(label);
panel.add(Box.createHorizontalGlue());

Forget all the LayoutManagers in the Java Standard Library and use MigLayout. In my experience it's much easier to work with an usually does exactly what you expect it to do.

Here's how to accomplish what you're after using MigLayout.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

public class Test
{
    public static void main( String[] args )
    {
        JFrame frame = new JFrame( );
        JPanel panel = new JPanel( );

        // use MigLayout
        panel.setLayout( new MigLayout( ) );

        // add the panel to the frame
        frame.add( panel );

        // create the label
        JLabel label = new JLabel( "Text" );

        // give the label MigLayout constraints
        panel.add( label, "push, align center" );

        // show the frame
        frame.setSize( 400, 400 );
        frame.setVisible( true );
    }
}

Most of that is just boilerplate. The key is the layout constraint: "push, align center":

align center tells MigLayout to place the JLabel in the center of its grid cell.

push tells MigLayout to expand the grid cell to fill available space.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!