JLabel自动换行
<img src="https://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();
	}
	
	
}
 
 

阅读更多
文章标签: java JLabel swing
个人分类: java知识
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

JLabel自动换行

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭