Question

While making a program, I noticed a bug with the JOptionPane.showMessageDialog() call. I use a button to create a JTextArea that wraps and then display a dialog containing this text area.

If the text area is too large, however, the dialog does not size itself correctly to the height of the JTextArea. The Dialog cuts off the OK button in this example.

I replicated the bug in the following code:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class DialogBug {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final String text = "looooooooooooooooooooooong text looooooooooooooooooooooooooooooooooooooong text";

        JButton button = new JButton();
        button.setPreferredSize(new Dimension(30, 30));

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextArea area = new JTextArea(text, 0, 50);
                area.setEditable(false);
                area.setLineWrap(true);
                area.setWrapStyleWord(true);
                area.append(text);
                area.append(text);
                area.append(text);

                JOptionPane.showMessageDialog(frame, area, "why does it do this", JOptionPane.WARNING_MESSAGE);
            }
        });

        frame.add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

I would post a picture, but I don't have enough reputation...

Is there a way to fix this without having to use a JScrollPane?

Here's a screenshot:

Was it helpful?

Solution

If you run the pack command on the dialog (a function in the Window class) it will resize based on subcomponents. For your case you will have to rewrite without using the showMessageDialog() to get the resize to work (so make the dialog first, add the text, pack, then show it)

Dialog b = new Dialog();
// add stuff
b.pack();

For my test code it worked perfectly to get the dialogs to be the right sizes

  1. Without pack() With Pack Command
  2. With pack() With Pack Command
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top