Despite that this is answered, I thought I d offer an alternative approach. This alternate boils down to put the text it in an HTML formatted label . The advantage of this approach is that line breaks are normally handled automatically, without having to worry about where to break each line. E.G.
import javax.swing.*;
class HeightOfFixedWidthText {
public static void show(String s) {
JLabel l = new JLabel(s);
l.setSize(l.getPreferredSize());
JOptionPane.showMessageDialog(null, l);
System.out.println(l.getSize());
}
public static void main(String[] srgs) {
String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla urna. Donec sit amet risus nisl, a porta enim. Quisque luctus, ligula eu scelerisque gravida, tellus quam vestibulum urna, ut aliquet sapien purus sed erat. Pellentesque consequat vehicula magna, eu aliquam magna interdum porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sollicitudin sapien non leo tempus lobortis. Morbi semper auctor ipsum, a semper quam elementum a. Aliquam eget sem metus.";
String html1 = "<html><body " +
"style= font-family: Serif; font-style: italic; font-size: 20px; padding: 0px; margin: 0px;" +
" width: ";
String html2 = "px >";
String html3 = "</body></html>";
show(html1+"200"+html2+s+html3);
show(html1+"300"+html2+s+html3);
}
}
Output
java.awt.Dimension[width=260,height=884]
java.awt.Dimension[width=390,height=544]
Caveat
- There is probably some (more) padding in the body of that HTML that needs to be removed in order to get the smallest size needed to display the the text. Left as an exercise for the user.
- Swing s HTML formatting is notorious for getting the baseline of text wrong. This is likely to count if the text content includes things like sub-scripts which drop below the usual baseline of the text. It seems as though that won t be a problem in this use-case.
- I only just noticed that though the width is specified as 200 then 300, the result comes back as 260 & 390. I could understand if that difference was constant between the two (extra padding to remove), but am quite mystified as to why it is different for each label.