Java JLabel, break text to next line?

折月煮酒 提交于 2020-01-21 06:37:19

问题


It's been awhile since I asked a question!

I'm developing an application in Java where JLabels are used. Anyway, as you may or may not be able to see from the picture below, the text that says Category Test gets cut off and ends up saying Categor... instead. Is there any way that I can "break" the text once it fills up the width of the label? Here is the image:

What I did

I used a JTextPane like so:

    JTextPane text = new JTextPane();
    SimpleAttributeSet attr = new SimpleAttributeSet();   

    StyleConstants.setAlignment(attr, StyleConstants.ALIGN_CENTER);  

    pane.add(text, c);

Then I added my text, but thanks anyway!


回答1:


JLabels can't do that by default. But JLabels have some support for html, so a JLabel with the text <html>First Line<br />Second Line</html> would show up on two lines.

If you want a component that can split the lines by itself, take a look at JTextArea.




回答2:


As I recall, you need to use a JTextArea if you want textwrap. JLabel doesn't do it.




回答3:


You can at StyledLabel component from JIDE Common Layer open source project at http://java.net/projects/jide-oss/.

The problem with html JLabel approach is it doesn't auto-wrap and about 20 to 40 times slower than a plain JLabel.

The problem with JTextArea or JTextPane approach is it has a weird size issue and is also 20 times slower.

StyledLabel extends JLabel. Automatically line wrapping is just one of the many features it adds. And the performance is as fast as a plain JLabel.

Hope it will help.



来源:https://stackoverflow.com/questions/9287461/java-jlabel-break-text-to-next-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!