Question

I have a JDialog with labels and buttons. I'm using MigLayout and I don't want the labels to be resized and mess up the rest of the layout (because I'm pretty sure they have enough space). I know that I could set the size to a fixed value, but my question is whether ther is a better solution for this (maby a better one with MigLayout, I don't want to have fixed sizes).

What I have in mind for a solution, but don't know how to do it: Create the panel with every component using all available space. But setText() will not cause a resizing of the labels. They should just stay as they are.

Working example:

public class ResizeDemo {

    public static void main(String[] args) {
        new ResizeDemo();
    }

    public ResizeDemo() {

        JDialog dialog = new JDialog();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setSize(600, 400);
        dialog.setResizable(false);
        dialog.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new MigLayout("wrap 2", "fill, grow", "fill, grow"));

        JLabel label1, label2;
        JButton longText1, shortText1, longText2, shortText2;

        label1 = new JLabel("Initial 1");
        label2 = new JLabel("Initial 2");

        longText1 = new JButton("longer Text");
        longText2 = new JButton("longer Text");
        shortText1 = new JButton("shorter Text");
        shortText2 = new JButton("shorter Text");

        longText1.addActionListener(new ChangeLabelListener(label1, "This is some longer Text than initial."));
        longText2.addActionListener(new ChangeLabelListener(label2, "This is some longer Text than initial."));
        shortText1.addActionListener(new ChangeLabelListener(label1, "Short text"));
        shortText2.addActionListener(new ChangeLabelListener(label2, "Short text"));

        panel.add(label1, "");
        panel.add(label2, "");
        panel.add(longText1, "");
        panel.add(longText2, "");
        panel.add(shortText1, "");
        panel.add(shortText2, "");

        dialog.setContentPane(panel);
        dialog.setVisible(true);
    }

}

class ChangeLabelListener implements ActionListener {

    private JLabel label;
    private String text;

    public ChangeLabelListener(JLabel label, String text) {
        this.label = label;
        this.text = text;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        this.label.setText(this.text);
    }
}
Was it helpful?

Solution

I should have waited to ask the question. I browsed through Mig Layout Whitepaper again and found the sizegroup component constraint.

Here is the solution:

//...
panel.add(label1, "sg label");
panel.add(label2, "sg label");
//...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top