Search code examples
javaswingjtextareajoptionpane

JOptionPane.showMessageDialog truncates JTextArea message


My Java GUI application needs to quickly show some text to the end-user, so the JOptionPane utility methods seem like a good fit. Moreover, the text must be selectable (for copy-and-paste) and it could be somewhat long (~100 words) so it must fit nicely into the window (no text off screen); ideally it should all be displayed at once so the user can read it without needing to interact, so scrollbars are undesirable.

I thought putting the text into a JTextArea and using that for the message in JOptionPane.showMessageDialog would be easy but it appears to truncate the text!

public static void main(String[] args) {
  JTextArea textArea = new JTextArea();
  textArea.setText(getText()); // A string of ~100 words "Lorem ipsum...\nFin."
  textArea.setColumns(50);
  textArea.setOpaque(false);
  textArea.setEditable(false);
  textArea.setLineWrap(true);
  textArea.setWrapStyleWord(true);
  JOptionPane.showMessageDialog(null, textArea, "Truncated!", JOptionPane.WARNING_MESSAGE);
}

Dialog with truncated text

How can I get the text to fit entirely into the option pane without scrollbars and selectable for copy/paste?


Solution

  • import java.awt.*;
    import javax.swing.*;
    
    public class TextAreaPreferredHeight2
    {
     public static void main(String[] args)
     {
      String text = "one two three four five six seven eight nine ten ";
      JTextArea textArea = new JTextArea(text);
      textArea.setColumns(30);
      textArea.setLineWrap( true );
      textArea.setWrapStyleWord( true );
      textArea.append(text);
      textArea.append(text);
      textArea.append(text);
      textArea.append(text);
      textArea.append(text);
      textArea.setSize(textArea.getPreferredSize().width, 1);
      JOptionPane.showMessageDialog(
       null, textArea, "Not Truncated!", JOptionPane.WARNING_MESSAGE);
     }
    }