Jlabel实现内容自动换行
Jlabel实现内容自动换行
版权声明:本文为博主原创文章,欢迎参考并提出意见。 https://blog.csdn.net/zhhtao89/article/details/50179695
在用java Swing写界面时,想实现JLabel中的文本内容自动换行,网上查了一下,大多是一些比较简单的加个
换行而已,于是自己写了一个函数,现在贴出了供大家学习。
效果图如下:
代码如下:
1 package com.zht; 2 3 import java.awt.BorderLayout; 4 import java.awt.Dimension; 5 import java.awt.FlowLayout; 6 import java.awt.FontMetrics; 7 import java.util.concurrent.TimeUnit; 8 9 import javax.swing.JFrame; 10 import javax.swing.JLabel; 11 12 public class JLabelDemo extends JFrame { 13 14 public static void main(String[] args) 15 throws InterruptedException { 16 System.out.println("hello"); 17 JLabelDemo jLabelDemo = new JLabelDemo(); 18 } 19 20 public JLabelDemo() throws InterruptedException { 21 String text = "This space contains technical articles," 22 + " blogs and discussion forums with questions and answers." 23 + "作为一个Java程序员,从论坛上感受到使用Java开发程序的人越来多," 24 + "心中不免欣慰。hello"; 25 JLabel label = new JLabel(); 26 label.setSize(200, 0);//注意JLabel一定要设置宽度 27 // System.out.println(label.getWidth()); 28 JlabelSetText(label, text); 29 setLayout(new FlowLayout()); 30 add(label); 31 pack(); 32 // setSize(300, 200); 33 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 34 setLocationRelativeTo(null); 35 setVisible(true); 36 } 37 38 void JlabelSetText(JLabel jLabel, String longString) 39 throws InterruptedException { 40 StringBuilder builder = new StringBuilder("<html>"); 41 char[] chars = longString.toCharArray(); 42 FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont()); 43 int start = 0; 44 int len = 0; 45 while (start + len < longString.length()) { 46 while (true) { 47 len++; 48 if (start + len > longString.length())break; 49 if (fontMetrics.charsWidth(chars, start, len) 50 > jLabel.getWidth()) { 51 break; 52 } 53 } 54 builder.append(chars, start, len-1).append("<br/>"); 55 start = start + len - 1; 56 len = 0; 57 } 58 builder.append(chars, start, longString.length()-start); 59 builder.append("</html>"); 60 jLabel.setText(builder.toString()); 61 } 62 }