Get height of multi line text with fixed width to make dialog resize properly

Lennart Schedin picture Lennart Schedin · Jun 26, 2009 · Viewed 7.3k times · Source

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: alt text
(source: lesc.se)

But I would like the dialog to look like this (as when you press the pack-button): alt text
(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.

Answer

Laurent K picture Laurent K · Jun 26, 2009

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

import static javax.swing.GroupLayout.DEFAULT_SIZE;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.text.View;

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

        Dimension prefSize = getPreferredSize(text.getText(), true, 400);

        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,DEFAULT_SIZE, prefSize.height, prefSize.height));
        layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(packMeButton)
                .addComponent(text, DEFAULT_SIZE, prefSize.width, prefSize.width) // 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);
            }
        });
    }

    private static final JLabel resizer = new JLabel();

    /**
     * Returns the preferred size to set a component at in order to render an html string. You can
     * specify the size of one dimension.
     */
    public static java.awt.Dimension getPreferredSize(String html, boolean width, int prefSize) {

        resizer.setText(html);

        View view = (View) resizer.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);

        view.setSize(width ? prefSize : 0, width ? 0 : prefSize);

        float w = view.getPreferredSpan(View.X_AXIS);
        float h = view.getPreferredSpan(View.Y_AXIS);

        return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));
    }
}