MigLayout对齐中心不会使JLabel组件居中 [英] MigLayout align center won't center JLabel component

查看:170
本文介绍了MigLayout对齐中心不会使JLabel组件居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MigLayout ,我觉得它很灵活,但是我在居中定位时遇到了问题它.我尝试使用gapleft 50%,但似乎百分比值需要在不同的帧大小上更改,因为它也取决于组件的大小.因此,如果使用gapleft 25%将组件居中放置,如果我调整框架宽度的大小,它将位于不同的位置.

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.

我尝试仅使用align center,它一点也没有.

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

我也尝试过new CC().alignX("center").spanX()和同样的事情:

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


(来源: gyazo.com )


(source: gyazo.com)

它一直向左移动,但是当我使用gapleft时它确实可以工作,为什么?

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

推荐答案

它一直向左移动,但是当我使用gapleft时它确实可以工作,为什么?

基于以下这一行:

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

默认情况下, MigLayout 行不会填充所有可用宽度,而仅是显示最长行的必要宽度(基于组件的宽度).话虽如此,您的JLabel适合徽标图像的宽度,仅此而已,并且看起来像是贴在左侧.您必须告诉布局管理器,在实例化它时必须填充所有可用宽度:

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

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

然后,您的组件约束将随着扩展而起作用.

Then, your component constraints will work as expexted.

基于此代码段:

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

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

这篇关于MigLayout对齐中心不会使JLabel组件居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆