I want to create a dialog that contains some kind of text element (JLabel/JTextArea etc) that is multi lined and wrap the words. I want the dialog to be of a fixed width but adapt the height depending on how big the text is. I have this code:
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextSizeProblem extends JFrame {
public TextSizeProblem() {
String dummyString = "";
for (int i = 0; i < 100; i++) {
dummyString += " word" + i; //Create a long text
}
JLabel text = new JLabel();
text.setText("<html>" + dummyString + "</html>");
JButton packMeButton = new JButton("pack");
packMeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pack();
}
});
GroupLayout layout = new GroupLayout(this.getContentPane());
getContentPane().setLayout(layout);
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(packMeButton)
.addComponent(text)
);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(packMeButton)
.addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400
);
pack();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new TextSizeProblem();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
When running the program it looks like this:
(source: lesc.se)
But I would like the dialog to look like this (as when you press the pack-button):
(source: lesc.se)
I'm guessing that the problem is that the layout manager had not been able to determine the proper height of the text before displaying it to the screen. I have tried various validate(), invalidate(), validateTree() etc but have not succeed.
I think this is what you want:
This will restrict the JLabel to being 200 pixels wide and automatically adjust the height to fit the text.
Here is an adaptation of your code, doing what you want. But it needs a little trick to calculate the size of the label and set its preferred Size.
I found the solution here
I found a solution to my problem. By replacing the JLabel with a JTextArea:
And calling pack() followed by an invocation to the layout manager to layout the components again followed by another pack:
This will cause the layout manager to adapt to the width.
The complete code:
(you can add some customization (border, color etc) so it looks just like the JLabel but I have omitted that)