简体   繁体   English

JLabel 将纯文本包装为 JTextArea

[英]JLabel wrapping plain text as JTextArea

I have a problem with JLabel and plain text wrapping in it.我对JLabel和纯文本包装有问题。 For plain text wrapping i am using LabelView and i am not very happy about the result it gives to me.对于纯文本换行,我使用的是LabelView ,但我对它给我的结果不是很满意。

My goal is to get plain text wrapping as in for example JTextArea .我的目标是获得纯文本换行,例如JTextArea I tried WrappedPlainView but it works only with JTextComponent我试过WrappedPlainView但它只适用于JTextComponent

So my question would be maybe you guys know/or have some advance JLabel views?所以我的问题是你们可能知道/或有一些预先的JLabel视图?

note: i do not want to add html to my plain text.注意:我不想将 html 添加到我的纯文本中。

LabelView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/LabelView.html标签视图: http : //docs.oracle.com/javase/6/docs/api/javax/swing/text/LabelView.html

WrappedPlainView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/WrappedPlainView.html WrappedPlainView: http ://docs.oracle.com/javase/6/docs/api/javax/swing/text/WrappedPlainView.html

Try this example and look how words are wrapped when frame is resized:试试这个例子,看看在调整框架大小时单词是如何包装的:

import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JTextArea textArea = new JTextArea(LONG_TEXT);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setOpaque(false);
    textArea.setEditable(false);

    add(new JScrollPane(textArea), BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}

Take a look to this example and you will see the problem with JLabel wrapping words:看看这个例子,你会看到 JLabel 包装词的问题:

import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JLabel label = new JLabel(LONG_TEXT);
    add(label, BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}

So the goal is to get JLabel words wrapping as in JTextArea.所以目标是让 JLabel 单词像在 JTextArea 中一样换行。

NOTE: in real project i am working with javax.swing.text.View`s and i am using LabelView for plain text.注意:在实际项目中,我正在使用 javax.swing.text.View`s 并且我使用 LabelView 作为纯文本。

So my question would be maybe you guys know/or have some advance JLabel views,所以我的问题是也许你们知道/或有一些预先的 JLabel 观点,

there are two ways,有两种方式,

  • use JTextComponent使用 JTextComponent

    1. non_editable, setEditable()不可编辑,setEditable()
    2. change setDisabledTextColor()更改 setDisabledTextColor()
    3. (only if needded) for transparency (JLabel is by default) you can to change opacity (仅在需要时)对于透明度(默认情况下为 JLabel),您可以更改不透明度

. .

  • use JLabel with Html (reduced and implemented up_to version Html3.2)将 JLabel 与 Html 一起使用(减少并实现了 Html3.2 版本)

  • post and SSCCE邮政和SSCCE

EDIT:编辑:

NOTE: in real project i am working with javax.swing.text.View`s and i am using LabelView for plain text.注意:在实际项目中,我正在使用 javax.swing.text.View`s 并且我使用 LabelView 作为纯文本。

for JTextComponents and javax.swing.text.Xxx is required to use intial PreferredSize , see public JTextArea(String text, int rows, int columns)对于JTextComponentsjavax.swing.text.Xxx需要使用初始PreferredSize ,请参阅public JTextArea(String text, int rows, int columns)

add 1) use JTextComponent添加 1) 使用 JTextComponent

there must be decision about必须做出决定

  • if wrapped in JScrollPane without or wihtout visible JScrollBar(override MouseScroll)如果包裹在JScrollPane没有或没有可见的 JScrollBar(覆盖 MouseScroll)

  • or simple added to container, I'd suggest to use BorderLayout or GridLayout, then JTextArea is resizable (looks like as) with container too或者简单地添加到容器中,我建议使用 BorderLayout 或 GridLayout,然后 JTextArea 也可以使用容器调整大小(看起来像)

  • scrollable JComponents will be added to JScrollPane可滚动的 JComponents 将被添加到 JScrollPane

.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class ExampleJTextArea extends JFrame {

    private /*static*/ final String LONG_TEXT = "Lorem ipsum dolor sit amet, "
            + "consectetur adipiscing elit. Ut in enim velit. Nunc posuere "
            + "purus ac odio dictum auctor. Vivamus nec sem mi. Curabitur sed "
            + "iaculis nibh. Proin vel massa augue. Aenean laoreet, tellus ut "
            + "vulputate mollis, justo eros ornare tortor, vitae venenatis "
            + "turpis augue id purus. In quis pretium justo. Quisque interdum "
            + "sem at augue ultrices molestie. Nulla consectetur magna nec est "
            + "malesuada sed ultricies diam gravida. Curabitur luctus, nulla "
            + "nec pulvinar fringilla, enim turpis luctus tellus, non auctor "
            + "diam ligula quis lectus.";

    public ExampleJTextArea() {
        JTextArea textArea = new JTextArea(LONG_TEXT, 10, 25);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setOpaque(false);
        textArea.setEditable(false);
        textArea.setBorder(new EmptyBorder(10,10,2,2));
        add(/*new JScrollPane(*/textArea/*), BorderLayout.CENTER*/);
        //setMinimumSize(new Dimension(100, 100));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ExampleJTextArea exampleJTextArea = new ExampleJTextArea();
            }
        });
    }
}

. .

. .

add 2) use JLabel with Html (reduced and implemented up_to version Html3.2), and another variations添加 2) 将 JLabel 与 Html 一起使用(减少并实现了 up_to 版本 Html3.2),以及其他变体

A very old thread, but in case anyone comes across this problem again...一个非常古老的线程,但万一有人再次遇到这个问题......

None of these solutions seemed to work for me (perhaps it is because the JPanel that contained my JLabel was viewed by a JScrollPane?), and I couldn't get JTextAreas working because it has some sort of fiddly bug where it grows but won't shrink.这些解决方案似乎都不适合我(也许是因为包含我的 JLabel 的 JPanel 被 JScrollPane 查看了?),而且我无法让 JTextAreas 工作,因为它有一些繁琐的错误,它在增长但不会“ t 收缩。

Instead, here is the easiest solution I could find for wrapping text in a JLabel, provided by Tony Fecteau on this page : Just use setPreferredSize() on a html-formatted JLabel and it'll start automatically growing and shrinking!相反,这是我能找到的最简单的 JLabel 包装文本解决方案,由 Tony Fecteau 在此页面上提供:只需在 html 格式的 JLabel 上使用setPreferredSize() ,它就会开始自动增长和缩小!

panel = new JPanel();
JLabel label = new JLabel("<html>" + "long text to display" + "</html>");
label.setPreferredSize(new Dimension(1, 1)); // this is the key part.
panel.add(label, "grow");

I also agree with @mKorbel that there are two ways to achieve the proper wrapping words through JLabel :我也同意@mKorbel 的观点,即有两种方法可以通过JLabel实现正确的换行:

a) Create your own custom component that emulates the JLabel style while wrapping. a) 创建您自己的自定义组件,在包装时模拟JLabel样式。

public class CustomWrappedLabel extends JTextArea {
    public CustomWrappedLabel(String text) {
        super(text);
        setBackground(null);
        setEditable(false);
        setBorder(null);
        setLineWrap(true);
        setWrapStyleWord(true);
        setFocusable(false);
    }
}

Usage :用法

new CustomWrappedLabel("Hey you've just tried multi-line text!");

Make sure that you set the amount of rows more than 2 lines to achieve the required behavior.确保将行数设置为超过 2 行以实现所需的行为。 wrappedLabelObj.setRows(2) . wrappedLabelObj.setRows(2) Use pack() to calculate the height of the parent component correctly.使用pack()正确计算父组件的高度。

b) Use html which automatically take care of wrapped text inside <html> tag. b) 使用 html 自动处理<html>标签内的包装文本。

new JLabel("<html>Hey you've just tried html multi-line text version!</html>")

You can use <br /> for newline.您可以使用<br />换行。

Hope this helps!希望这可以帮助!

试试这个

jLabel.setText(String.format("<html><body style=\"text-align: justify;  text-justify: inter-word;\">%s</body></html>",LONGTEXT));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM