MigLayout align center won't center JLabel component

血红的双手。 提交于 2019-12-24 07:15:42

问题


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:


(source: gyazo.com)

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:


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);


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);


来源:https://stackoverflow.com/questions/24976391/miglayout-align-center-wont-center-jlabel-component

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