Silver moon
Silver moon

Reputation: 229

MigLayout: Put two JLabel on the same line separated by JTextField

How do I set two JLabels separated by a JTextField in the same line? I am using MigLayout. I have the following code

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

The output that I get looks like the following.

enter image description here

I want the icon on the same line as Threshold and the text field. How should I adjust it? Any help/suggestions are appreciated.

Upvotes: 0

Views: 156

Answers (1)

MobiusOne
MobiusOne

Reputation: 48

Have you looked into using row/column constraints and using "cell" arguments when placing the Components? I've had a lot of success with that method.

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

Make a point of reading both the MigLayout Whitepaper and MigLayout Quick Start Guide, as they do a really good job of explaining everything at your disposal.

Sidenotes:

  1. The reason it's not showing up in one line is because you're telling MigLayout it's okay to wrap the Components to fit in the space you're giving it, including making new lines to accommodate. You could also try increasing the size of the window.

  2. The size 100:20 translates to 100px minimum size, but a 20px preferred size, and I don't know how MigLayout would handle that. I changed it in my code.

(Disclaimer: code is untested and may be a little rough)

Upvotes: 1

Related Questions