Search code examples
javaswinguser-interfacejcomponentmiglayout

How do I fill a spanning area with a background colour In MigLayout?


This is a screenshot of my current interface:

Screenshot

My JLabel targetJlabel is contained by a rectangle of property spany 2 with a red dotted border (I think, the rectangle is called a JComponent?), and I'd like to fill all of that rectangle with a colour. However, I can't see how to set the background colour on anything but the JLabel itself.

Here is my SSCCE:

package com.sample;

import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.*;

public class App
{
    public static void main( String[] args ) {
        App program = new App();
        SwingUtilities.invokeLater(program::run);
    }

    private void run() {
        JFrame w = new JFrame();
        w.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel d = new JPanel();
        d.setLayout(new MigLayout(
                "debug, fill",
                "[min!][min!][min!][min!][min!]",
                "[][][grow]"));

        JLabel targetJlabel = new JLabel("I want this colour to fill up to the dotted red line");
        targetJlabel.setBackground(Color.CYAN);
        targetJlabel.setOpaque(true);
        d.add(targetJlabel, "spany 2");

        d.add(new JTextField("type here"), "growx, spanx 3");

        d.add(new JButton("Search"), "spany 2, wrap");

        d.add(new JCheckBox("box1"));
        d.add(new JCheckBox("box2"));
        d.add(new JCheckBox("box3"), "wrap");

        w.add(d);
        w.pack();
        w.setVisible(true);
    }
}

Solution

  • This little change does the trick :-)

     d.add(targetJlabel, "growy, spany 2");
    

    enter image description here