通过设置最大宽度使 JLabel 包裹它的文本 [英] make a JLabel wrap it's text by setting a max width

查看:26
本文介绍了通过设置最大宽度使 JLabel 包裹它的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JLabel,上面有很多文字.有没有办法让 JLabel 有一个最大宽度,这样它就会包裹文本,使其不超过这个宽度?

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?

谢谢

推荐答案

没有.

您可以在标签中使用 HTML,但您必须对中断标记进行硬编码.

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

更好的方法是使用 JTextArea 并打开环绕.您可以更改文本的背景、前景、字体等,使其看起来像一个标签.

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.

请注意,此答案至少在 Java 7 中已过时.

根据@darren 的回答,您只需要用 <html></html> 标签包装字符串:

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.

这篇关于通过设置最大宽度使 JLabel 包裹它的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆