java jlabel如何换行,如何在JLabel中自动换行?

How can text like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" which exceeds the width of the JLabel be wrapped?

I have tried enclosing the text into html tags but no luck.

Please give your suggestions.

解决方案

A common approach is to not use a JLabel and instead use a JTextArea with word-wrap and line-wrap turned on. You could then decorate the JTextArea to make it look like a JLabel (border, background color, etc.). [Edited to include line-wrap for completeness per DSquare's comment]

Another approach is to use HTML in your label, as seen here. The caveats there are

You may have to take care of certain characters that HTML may interpret/convert from plain text

Calling myLabel.getText() will now contain HTML (with possibly

escaped and/or converted characters due to #1

EDIT: Here's an example for the JTextArea approach:

MvbxV.png

import javax.swing.*;

public class JLabelLongTextDemo implements Runnable

{

public static void main(String args[])

{

SwingUtilities.invokeLater(new JLabelLongTextDemo());

}

public void run()

{

JLabel label = new JLabel("Hello");

String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

// String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " +

// "quick brown fox jumped over the lazy dog.";

JTextArea textArea = new JTextArea(2, 20);

textArea.setText(text);

textArea.setWrapStyleWord(true);

textArea.setLineWrap(true);

textArea.setOpaque(false);

textArea.setEditable(false);

textArea.setFocusable(false);

textArea.setBackground(UIManager.getColor("Label.background"));

textArea.setFont(UIManager.getFont("Label.font"));

textArea.setBorder(UIManager.getBorder("Label.border"));

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(label, BorderLayout.NORTH);

frame.getContentPane().add(textArea, BorderLayout.CENTER);

frame.setSize(100,200);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值