简体   繁体   中英

Word-wrap radio button text in Java?

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.

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 );
    }
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM