Hi, i want to JLabel text in multiline otherwise text wiill be so long,how can do this in java?
Thanks, Rekha
Hi, i want to JLabel text in multiline otherwise text wiill be so long,how can do this in java?
Thanks, Rekha
private void wrapLabelText(JLabel label, String text) {
FontMetrics fm = label.getFontMetrics(label.getFont());
Container container = label.getParent();
int containerWidth = container.getWidth();
BreakIterator boundary = BreakIterator.getWordInstance();
boundary.setText(text);
StringBuffer trial = new StringBuffer();
StringBuffer real = new StringBuffer("<html>");
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE;
start = end, end = boundary.next()) {
String word = text.substring(start,end);
trial.append(word);
int trialWidth = SwingUtilities.computeStringWidth(fm,
trial.toString());
if (trialWidth > containerWidth) {
trial = new StringBuffer(word);
real.append("<br>");
}
real.append(word);
}
real.append("</html>");
label.setText(real.toString());
}
I suggest to use a JTextArea instead of a JLabel
and on your JTextArea you can use the method .setWrapStyleWord(true) to change line at the end of a word.
Displaying Multi Line Text contains 4 different approaches to achieve this.
If you don't mind wrapping your label text in an html
tag, the JLabel will automatically word wrap it when its container's width is too narrow to hold it all. For example try adding this to a GUI and then resize the GUI to be too narrow - it will wrap:
new JLabel("<html>This is a really long line that I want to wrap around.</html>");