문제

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?

도움이 되었습니까?

해결책

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);
 }
}

다른 팁

If you need to display a string of an unknown length, you can set number of rows "on the fly":

public static void showMessageDialogFormatted(String msg, String title, int messageType, int columnWidth) {
    JTextArea textArea = new JTextArea(msg);
    textArea.setColumns(columnWidth);
    textArea.setRows(msg.length() / columnWidth + 1);
    textArea.setLineWrap(true);
    textArea.setEditable(false);
    textArea.setWrapStyleWord(true);
    JOptionPane.showMessageDialog(null, textArea, title, messageType);
}

You've got the right idea. Just adjust the rows of your textarea.

textArea.setRows(10); // or value that seems acceptable to you...

This seemed to fix the issue for me, using 100 words of lorem ipsum.

Try this:

JTextArea textArea = new JTextArea();
textArea.setText(getText());
textArea.setSize(limit, Short.MAX_VALUE); // limit = width in pixels, e.g. 500
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top