Re: Layout labels with variable text length
On Aug 7, 7:31 pm, Simon <count.numb...@web.de> wrote:
...
I would like to say something like "make the width of the label N
columns and make it as high as necessary". This must be possible
somehow, and it must be a frequently occurring problem, but I have never
seen it discussed anywhere. Any ideas?
This answer needs some style, or at least, it
needs *a* style.
<sscce>
import java.awt.*;
import javax.swing.*;
public class BreakLabelTest {
static String labelText =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Donec elementum porta suscipit. " +
"</p><p>Sed nec lorem libero. Nulla facilisi. Donec tristique" +
" lectus eget nibh cursus semper. " +
"Suspendisse pulvinar enim vel eros imperdiet suscipit." +
" Morbi et sollicitudin urna.";
public static void main(String[] args) {
JFrame f = new JFrame("Line Breaks");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout());
JTextField tf = new JTextField(15);
p.add( tf, BorderLayout.NORTH );
int width = (int)tf.getPreferredSize().getWidth();
JLabel label = new JLabel(
"<html><body>" +
// this does the magic..
"<div style='width: " + width + "'>" +
labelText);
p.add(new JScrollPane(label), BorderLayout.CENTER);
f.add(p);
f.pack();
f.setVisible(true);
}
}
</sscce>
--
Andrew T.
pscode.org