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