首页 > 解决方案 > MigLayout:将两个 JLabel 放在由 JTextField 分隔的同一行上

问题描述

如何在同一行中设置两个由 JTextField 分隔的 JLabel?我正在使用 MigLayout。我有以下代码

		JPanel helper = new JPanel( new MigLayout() );
		helper.add( new JLabel( "Threshold:" ), "" );
		threshold = new JTextField();
		Icon thresholdIcon = UIManager.getIcon( "OptionPane.questionIcon" );
		JLabel thresholdIconLabel = new JLabel( thresholdIcon );
		thresholdIconLabel.setToolTipText( "Threshold for template matching" );
		helper.add( threshold, "wrap, width 100:20" );
		helper.add( thresholdIconLabel, "wrap, width 100:20" );

我得到的输出如下所示。

在此处输入图像描述

我希望图标与阈值和文本字段位于同一行。我应该如何调整它?任何帮助/建议表示赞赏。

标签: javauser-interfacejlabeljtextfieldmiglayout

解决方案


您是否考虑过在放置组件时使用行/列约束并使用“单元格”参数?我用这种方法取得了很大的成功。

    JPanel helper = new JPanel(
            new MigLayout(
                    "", 
                    "5[grow,fill]10[grow,fill,20:100]10[grow,fill,20:100]5",
                    "5[fill,grow]5"));
    helper.add( new JLabel( "Threshold:" ), "cell 0 0" );
    threshold = new JTextField();                  // Assuming this was declared earlier
    Icon thresholdIcon = UIManager.getIcon( "OptionPane.questionIcon" );
    JLabel thresholdIconLabel = new JLabel( thresholdIcon );
    thresholdIconLabel.setToolTipText( "Threshold for template matching" );
    helper.add( threshold, "cell 1 0" );
    helper.add( thresholdIconLabel, "cell 2 0" );

请务必阅读MigLayout 白皮书MigLayout 快速入门指南,因为它们很好地解释了您可以使用的所有内容。

旁注:

  1. 它没有出现在一行中的原因是因为您告诉 MigLayout 可以让wrap组件适应您给它的空间,包括制作新的行来适应。您也可以尝试增加窗口的大小。

  2. 尺寸100:20转换为 100px 最小尺寸,但 20px 首选尺寸,我不知道 MigLayout 将如何处理。我在我的代码中更改了它。

(免责声明:代码未经测试,可能有点粗糙)


推荐阅读