Jlabel实现内容自动换行简单实例

时间:2022-04-02 08:42:52

在用javaswing写界面时,想实现jlabel中的文本内容自动换行,网上查了一下,大多是一些比较简单的加个换行而已,于是自己写了一个函数,现在贴出了供大家学习。

效果图如下:

Jlabel实现内容自动换行简单实例

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.zht;
import java.awt.borderlayout;
import java.awt.dimension;
import java.awt.flowlayout;
import java.awt.fontmetrics;
import java.util.concurrent.timeunit;
import javax.swing.jframe;
import javax.swing.jlabel;
public class jlabeldemo extends jframe {
    public static void main(string[] args)
       throws interruptedexception {
        system.out.println("hello");
        jlabeldemo jlabeldemo = new jlabeldemo();
    }
    public jlabeldemo() throws interruptedexception {
        string text = "this space contains technical articles,"
            + " blogs and discussion forums with questions and answers."
            + "作为一个java程序员,从论坛上感受到使用java开发程序的人越来多,"
            + "心中不免欣慰。hello";
        jlabel label = new jlabel();
        label.setsize(200, 0);
        //注意jlabel一定要设置宽度
        //  system.out.println(label.getwidth());
        jlabelsettext(label, text);
        setlayout(new flowlayout());
        add(label);
        pack();
        //  setsize(300, 200);
        setdefaultcloseoperation(jframe.exit_on_close);
        setlocationrelativeto(null);
        setvisible(true);
    }
    void jlabelsettext(jlabel jlabel, string longstring)
       throws interruptedexception {
        stringbuilder builder = new stringbuilder("<html>");
        char[] chars = longstring.tochararray();
        fontmetrics fontmetrics = jlabel.getfontmetrics(jlabel.getfont());
        int start = 0;
        int len = 0;
        while (start + len < longstring.length()) {
            while (true) {
                len++;
                if (start + len > longstring.length())break;
                if (fontmetrics.charswidth(chars, start, len)
                      > jlabel.getwidth()) {
                    break;
                }
            }
            builder.append(chars, start, len-1).append("<br/>");
            start = start + len - 1;
            len = 0;
        }
        builder.append(chars, start, longstring.length()-start);
        builder.append("</html>");
        jlabel.settext(builder.tostring());
    }
}

总结

以上就是本文关于jlabel实现内容自动换行简单实例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/zhhtao89/article/details/50179695