1

I have a JOptionPane.showConfirmDialog. It has to display a very long string. They length varies. So what I did was create a textArea, add the string to text area. I don't want to do setColumns, setRows.

Is there a way dynamically adjust the size? Do advice . Thanks!

String longString="asdas";//Long string. 
JTextArea textArea = new JTextArea(longString);
/*want to avoid setting the size*/
//textArea.setColumns(70);
// textArea.setRows(5);
textArea.setLineWrap( true );
textArea.setBackground(null);
textArea.setFont(null);
textArea.setWrapStyleWord( true );

int l_iResult = JOptionPane.showConfirmDialog( this, textArea , "Confirm Delete", 
                                                            JOptionPane.YES_NO_OPTION );
Lahiru Ashan
  • 602
  • 9
  • 16
Jacel
  • 197
  • 2
  • 5
  • 18
  • create your own message window lolz :D which is customizeable – Zain Ul Abidin Nov 07 '16 at 06:00
  • *"I don't want to do `setColumns`, `setRows`"* Why not? BTW - consider using a `JLabel` with HTML formatting and setting a width to the `body` it will be as wide as specified, but only as tall as needed. Here is [an example](http://stackoverflow.com/questions/7861724/is-there-a-word-wrap-property-for-jlabel/7861833#7861833).. – Andrew Thompson Nov 07 '16 at 07:54
  • If i set 300 columns, 100 rows, then i will have a big box, with small text and lot of empty space – Jacel Nov 07 '16 at 07:59

1 Answers1

1
JTextArea textArea = new JTextArea(longString);
textArea.setSize( new Dimension(200, 16) );

Looks like if you specify a width around 200 (or greater) the text area will be able to calculate its height allowing for the wrapping of the text.

camickr
  • 308,339
  • 18
  • 152
  • 272
  • @Jacel, Define long? it worked for me using JDK8 on Windows 7. I copied the text from your first paragraph (twice) and It wrapped the text onto 13 lines. – camickr Nov 07 '16 at 06:32
  • You may need to do: textArea.setPreferredSize(new Dimension(600, 300)); which for me makes a pretty darn big dialog :) – DevilsHnd Nov 07 '16 at 06:43
  • Yes,, textArea.setPreferredSize(new Dimension(600, 300)); is a solution, but if you have small text..just length:10, then u have a small text in a humongous empty box. – Jacel Nov 07 '16 at 08:00
  • @DevilsHnd, Nowhere did I suggest to use setPreferredSize, you should not be doing that. Each component is responsible for determining it own preferred size. My solution is to give a suggestion by setting the size, then the text area will determine its own preferred size based on the specified width. Don't clutter the answer with your own guess because now the OP is ignoring my working solution and hasn't responded to my further question. Post your own answer. – camickr Nov 07 '16 at 15:16