简体   繁体   中英

How to display text with line-breaks in java

I'm working on a text-editor, and I want to display the typed text, what can contain line/breaks. But JLabel does not show multiline text (without using HTML - but I don't want to use). I tried displaying it in an uneditable JTextArea (in a JScrollPane), but it became unscrollable with mouse wheel.

For example:

JTextArea textArea = new JTextArea();
JLabel label = new JLabel(textArea.getText());
JFrame.add(new JScrollPane(label));

How can I display multiline text in a scrollable container?

It's hard to say why your JTextArea would stop scrolling, maybe it's a separate issue. This should work fine.

package test;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            JTextArea ta = new JTextArea("a\nb\nc\nd\ne\nf\ng\nh");
            ta.setEditable(false);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            p.add(new JScrollPane(ta));
            f.add(p);
            f.setSize(100, 100);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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