关闭

JLabel自动换行

标签: javaJLabelswing
1530人阅读 评论(0) 收藏 举报
分类:
<img src="http://img.blog.csdn.net/20150707012645217?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
package jlabel;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;


/**
 * 测试类
 *
 */
public class TesthtmlLabel extends JFrame{
	
	private static final long serialVersionUID = 1L;

	/**
	 * 将JLabel文本按照width宽度自动换行,会改变label的preferredSize为width,高度按照内容自动计算
	 * @param width 设定的换行宽度
	 * @param label 目标JLabel
	 * @return width<=0 或label为null时,返回label
	 */
	public JLabel createJLabelWithWrapWidth(int width, JLabel label){
		if (width <= 0 || label == null){
			return label;
		}
		String text = label.getText();
		if (!text.startsWith("<html>")){
			StringBuilder strBuilder = new StringBuilder("<html>");
			strBuilder.append(text);
			strBuilder.append("</html>");
			text = strBuilder.toString();
		}
		label.setText(text);
		View labelView = BasicHTML.createHTMLView(label, label.getText());
		labelView.setSize(width, 100);
		label.setPreferredSize(new Dimension(width, (int) labelView.getMinimumSpan(View.Y_AXIS)));
	    return label;
	}
	public TesthtmlLabel(){
		
		JLabel label = new JLabel();
		label.setText("a very1 very2 very3 very4 very5 very6 very7 very8 long9 string");
		label = createJLabelWithWrapWidth(200, label);
		JLabel label1 = new JLabel();
		label1.setText("a very1 very2 very3 very4 very5 very6 very7 very8 long9 string");
		label1 = createJLabelWithWrapWidth(200, label1);
		JLabel label2 = new JLabel();
		label2.setText("a very1 very2 very3 very4 very5 very6 very7 very8 long9 string");
		label2 = createJLabelWithWrapWidth(200, label2);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("超链接标签");
		this.setLayout(new FlowLayout(FlowLayout.TRAILING,50,50));
		this.add(createJLabelWithWrapWidth(200, label));
		this.add(createJLabelWithWrapWidth(180, label1));
		this.add(createJLabelWithWrapWidth(160, label2));
		this.pack();
		this.setVisible(true);
	}
	public static void main(String[] args){
		new TesthtmlLabel();
	}
	
	
}
 
 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8643次
    • 积分:139
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:2篇
    • 译文:0篇
    • 评论:4条
    文章存档
    最新评论