I am looking for a way to do the following:
Have a JDialog with a fixed width.
In it is a JTextArea (or whatever you suggest is a better component...) which receives a text of varying length (somewhere between 0 and 30 line)
Below that text is a button.
The dialog is automatically sized in height to make sure all the Text AND the button is being displayed.
The closest I have come to a solution is this, but the JTextArea does not seem to know how large it is after it did the automatic line breaks!
public PleaseResize(){
super();
Container cp = this.getContentPane();
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
JTextArea area = new JTextArea();
area.setColumns(20);
area.setLineWrap(true);
area.setEditable(false);
area.setWrapStyleWord(true);
area.setText("Once upon a midnight dreary, while I pondered, weak and weary, over many a quaint an curious volume of forgotten lore.");
cp.add(area);
cp.add(new JButton("Hallo"));
this.pack();
}
Scrolling the Text is unfortunately not an option.
I have asked this is a slightly different way before here: Resize Dialog properly after automatic LineWrap, but perhaps the JTextArea is the wrong component after all? Am I using the wrong LayoutManager? All of them seem unable to determine how large the dialog should be, though. Why does the JTextArea fail to communicate it's height after adding line-breaks to the text to the outside?
Here is the working code:
public PleaseResize() throws BadLocationException {
super();
Container cp = this.getContentPane();
cp.setLayout(new BorderLayout());
JTextArea area = new JTextArea();
area.setColumns(20);
area.setLineWrap(true);
area.setEditable(false);
area.setWrapStyleWord(true);
area.setText("Once upon a midnight dreary, while I pondered, weak and weary, over many a quaint an curious volume of forgotten lore.");
System.out.println(area.getLineCount());
JScrollPane pane = new JScrollPane(area);
cp.add(pane, BorderLayout.CENTER);
cp.add(new JButton("Hallo"), BorderLayout.SOUTH);
this.pack();
this.pack();
}
Packing twice still seems a bit weird to me, but it does solve the resizing problems :).