如何在没有HTML的情况下获得多线JLabel(或看起来完全相同的JTextArea) [英] How to get a multilined JLabel (or a JTextArea looking totally the same) without HTML

查看:131
本文介绍了如何在没有HTML的情况下获得多线JLabel(或看起来完全相同的JTextArea)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能相信多线JLabel的最快解决方案是以下一个(文本来自var,所以我不想每个x字符手动放置HTML代码,它太丑了):

I cant believe fastest solution for a multilined JLabel is the following one (text comes from a var, and so I dont want to put HTML code manually every x chars, its so ugly):

public class JMultilineLabel extends JTextArea{
    private static final long serialVersionUID = 1L;
    public JMultilineLabel(String text){
        super(text);
        setEditable(false);  
        setCursor(null);  
        setOpaque(false);  
        setFocusable(false);  
        setFont(UIManager.getFont("Label.font"));      
        setWrapStyleWord(true);  
        setLineWrap(true);
    }
} 

...确定它不是更好的处理方式这个????

... sure it isnt a better way to handle this????

推荐答案

如果你想要一个multilne标签,那么你只需使用 HTML 在其文本中,因为它们支持其使用。因此,使用线制动器标签< / br> 来打破行或在< p>< / p> 段落标记。

If you want a multilne label then you simply use HTML in its text, as they support its use. Therefore, use line brake tag </br> to break lines or put separate lines in <p></p> paragraph tags.

不要忘记标记您要将HTML用于 JLabel by使用< html> 标记开始发送文字。

Do not forget to mark that you want to use HTML for a JLabel by starting its text with the <html> tag.

这里有更多信息。

顺便说一句我忘了检查是否有关于 JLabel 使用的其他相关问题并且至少有一些,请检查这个这个。 :)

BTW I forgot to check if there were other related questions about JLabel use and there were at least a few, check this or this. :)

编辑:

对于工作样本,显示不同的方法,不设置样式并使用段落和标签占用可用空间,请参见下文:

For a working sample, showing a different approach, without setting a style and with use of paragraph and label taking available space, please see below:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;

public class LabelHTMLAutoResize {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel p = new JPanel(new BorderLayout());
                JLabel l = new JLabel("<html><p> Some verrrry long text  Some verrrry long  Some verrrry long text dsa ads oiosi o</p>");
                l.setVerticalAlignment(SwingConstants.TOP);
                l.setOpaque(true);
                l.setBackground(Color.green);
                p.add(l);
                f.setContentPane(p);
                /* good practice is to use f.pack(); and let the size be automatically calculated but we want to show line wrapping thus frame size is set */
                f.setSize(200, 200);
                f.setVisible(true);
            }
        });
    }
}

这篇关于如何在没有HTML的情况下获得多线JLabel(或看起来完全相同的JTextArea)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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