如何在JLabel中自动换行? [英] How to word wrap text in JLabel?

查看:270
本文介绍了如何在JLabel中自动换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何包装超过JLabel宽度的文本"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 我尝试将文本包含在html标签中,但是没有运气. 请提出您的建议.

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.

推荐答案

一种常见的方法是不使用JLabel而是使用JTextArea并启用自动换行和自动换行.然后,您可以装饰JTextArea以使其看起来像JLabel(边框,背景色等). [已编辑,以根据DSquare的评论包含换行符,以确保完整性]

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.).

另一种方法是在标签中使用HTML,如在此处看到.注意事项

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

  1. 您可能需要照顾HTML可以从纯文本解释/转换的某些字符

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

调用myLabel.getText()现在将包含HTML(可能 #1

Calling myLabel.getText() will now contain HTML (with possibly escaped and/or converted characters due to #1

编辑:以下是JTextArea方法的示例:

Here's an example for the JTextArea approach:

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);
  }
}

这篇关于如何在JLabel中自动换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆