make a JLabel wrap it's text by setting a max width

后端 未结 9 2514
清酒与你
清酒与你 2020-11-29 08:09

I have a JLabel which has a lot of text on it. Is there a way to make the JLabel have a max width so that it will wrap the text to make it not exceed this width?

Tha

相关标签:
9条回答
  • 2020-11-29 08:33

    JXLabel in the SwingX project supports wrapping

    JXLabel label = new JXLabel(somelongtext);
    label.setLineWrap(true);  
    
    0 讨论(0)
  • 2020-11-29 08:40

    There's a good technique here, scroll to the end of the article.

    JLabel labelBeingUsed = myLabel;
    View view = (View) labelBeingUsed.getClientProperty(BasicHTML.propertyKey);
    view.setSize(scrollPane1.getWidth(), 0.0f);
    float w = view.getPreferredSpan(View.X_AXIS);
    float h = view.getPreferredSpan(View.Y_AXIS);
    labelBeingUsed.setSize((int) w, (int) h);
    
    0 讨论(0)
  • 2020-11-29 08:43

    No.

    You can use HTML in the label, but then you must hard code the break tag.

    A better approach is to use a JTextArea and turn wrapping on. You can change the background,foreground, font etc. of the text are to make it look like a label.

    Note, this answer is outdated as of at least Java 7.

    As per @darren's answer, you simply need to wrap the string with <html> and </html> tags:

    myLabel.setText("<html>"+ myString +"</html>");
    

    You do not need to hard-code any break tags. The text wraps as the component resizes.

    0 讨论(0)
提交回复
热议问题