MigLayout align center won't center JLabel com

2019-08-05 18:13发布

I am using MigLayout I find it flexible etc,but I am having a problem with centring stuff with it. I tried using gapleft 50% but it seems like the percent number needs to change on different frame sizes, because it's also depending on component's size. so if the component is centred using gapleft 25%, it will be on a different location if i resize the width of my frame.

I've tried using just align center and it doesn't nothing at all.

I've also tried new CC().alignX("center").spanX() and same thing:

img http://gyazo.com/8b562b6dd319d0af1d85cba930af0328.png

It's sticks to left, however it does work when I use gapleft, why?

    super.setLayout(new MigLayout());
    this.loginPane = new LoginPanel();

    BufferedImage logo = ImageIO.read(new File("assets/logo.png"));
    JLabel logoLabel = new JLabel(new ImageIcon(logo));

    super.add(logoLabel, new CC().alignX("center").spanX());

1条回答
我只想做你的唯一
2楼-- · 2019-08-05 19:04

It's sticks to left, however it does work when I use gapleft, why?

Based on this single line:

super.setLayout(new MigLayout()); // why super? Did you override setLayout() method?

By default MigLayout rows doesn't fill all available width but only the necessary to display the longest row (based on components width). Having said this your JLabel fits the logo image width and nothing more and it looks like stick to left side. You have to tell the layout manager that it has to fill all available width when you instantiate it:

super.setLayout(new MigLayout("fillx"));

Or

LC layoutConstraints = new LC();
layoutConstraints.setFillX(true);
super.setLayout(new MigLayout(layoutConstraints);

Then, your component constraints will work as expexted.


Picture

Based on this code snippet:

MigLayout layout = new MigLayout("fillx, debug");
JPanel content = new JPanel(layout);

JLabel label = new JLabel("Warehouse");
label.setFont(label.getFont().deriveFont(Font.BOLD | Font.ITALIC, 18));

CC componentConstraints = new CC();
componentConstraints.alignX("center").spanX();
content.add(label, componentConstraints);

enter image description here


Note: you can enable debug feature by doing this:

super.setLayout(new MigLayout("fillx, debug"));

Or

LC layoutConstraints = new LC();
layoutConstraints.setFillX(true);
layoutConstraints.setDebugMillis(500);
super.setLayout(new MigLayout(layoutConstraints);
查看更多
登录 后发表回答