Im working on a Marquee JPanel ,and im using a JLabel to scroll Text within the JPanel by Decreasing the Y of JLabel inside the JPanel .
The issue is i need a Specific Width of JLabel where Height is not important because it will scroll the Text until the Y of JLabel is > than -JLabel.Height which means JLabel last line of text is at Top of JPanel .
So how can i calculate the Height which can hold a sort of Text based on a specific value of Width .
eg. If Width of JLabel is 50 than the Height should be that value that can fit the text within if text is "Bla bla bla some text over ..." and font is "Serif", Font.ITALIC, 20
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);
}
}
java.awt.Dimension[width=260,height=884]
java.awt.Dimension[width=390,height=544]
You may want to look at the FontMetrics class, which has methods for getting attributes of the font such as height, width, ascent, etc. based on font size. Given this information you should be able to work out the height of a particular font / size relative to the width, and vice versa.
The Dimension
that you get back from from getPreferredSize()
should be valid anytime after you call pack()
or validate()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With