views:

688

answers:

3

I have some radio buttons whose text may be very long. Is there an easy way to word-wrap them?

Yes, wrapping them in <html> tags and inserting <br> tags would work, but is there a more automatic way to accomplish this? I don't really want to roll my own typesetter.

A: 

Wrapping them in <html> tags and making sure they get enough vertical space should work. No need to break the lines yourself.

Aaron Digulla
Can you provide a code sample? I tried this with practically every Layout and this didn't work with any of them.
Amanda S
+1  A: 

I don't think that there are any perfect solutions for this. Other than using <br> tags, you could use a JTextArea and make it look like a label. Then set lineWrap and wrapStyleWord to true.

Then, you lose the functionality of clicking on the labels to select/deselect your radio button, so you will have to add a mouse listener.

thedude19
+3  A: 

The quickest and dirtiest way is simply to prepend <html> at the start of the radio button's label text. This will make line wrapping start to occur but you'll now need to be careful about that text if it has < characters in it. This also maintains the functionality of click on the label text being a click on the radio button.

Here's a cheap and cheerful example:

public class Test extends JFrame {
    public static void main(String[] args) {
        new Test();
    }

    private Test() {
        Container  c = getContentPane();
        c.setLayout( new BorderLayout() );
        c.add( new JRadioButton( "<html>I've got a very long text description that's going to wrap over very long lines because I stuck an &lt;html&gt; tag at the start of its label string.</html>") );
        setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        setSize( 200,200 );
        setVisible( true );
    }
}
banjollity
Works very well and is a short solution. It's dirty and would work if you put an </html> at the end. it would be nicer ;)
furtelwart
Since you asked so nicely! :)
banjollity