Search code examples
javaswingjoptionpanemiglayout

MigLayout causes exception in JOption pane when JTextArea is used. FlowLayout is just fine


The sample program below displays a frame with two buttons. Pressing the second button which uses MigLayout causes an exception. The first button which uses FlowLayout works just fine. Appears to be a bug in MigLayout?

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import net.miginfocom.swing.MigLayout;

public class Main extends JPanel {

static private JFrame frame = new JFrame("Test MigLayout");

public Main() {
    JButton flowLayoutButton = new JButton("FlowLayout");
    JButton miglayoutButton = new JButton("MigLayout");
    add(flowLayoutButton);
    add(miglayoutButton);
    flowLayoutButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEventIn) {
            showDialog(false);
        }
    });
    miglayoutButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEventIn) {
            showDialog(true);
        }
    });
}

public static void main(String[] args) {
    Main main = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(main);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            frame.pack();
            frame.setVisible(true);
            frame.setBounds(200, 200, 200, 200);
        }
    });
}
private void showDialog(boolean useMidgLayoutIn) {
    JPanel panel = new JPanel(useMidgLayoutIn ? new MigLayout() : new FlowLayout());
    JTextArea topTextArea = new JTextArea("Here is some junk text to fill up the Text Area.");
    panel.add(topTextArea);
    panel.add(new JButton("Button"));

    JOptionPane optionPane = new JOptionPane(panel, JOptionPane.ERROR_MESSAGE);
    JDialog dialog = optionPane.createDialog(frame, "Application  Error");
    dialog.setResizable(true);
    dialog.pack();
    dialog.setVisible(true);
}
}

Solution

  • MigLayout 5.0 has compensation for this. It's in the trunk at Google Code if you want to test it.

    Cheers, Mikael