For multi-line text, you can use the JTextArea
even. In order for the line break to be made to adapt the text to the size of its component, call the method setLineWrap
and setWrapStyleWord
of JtextArea
, passing true
as a parameter.
See an example:
import java.awt.Dimension;
import javax.swing.*;
public class JTextAreaTest {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextArea Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String text = "Lorem Ipsum is simply dummy text of "
+ "the printing and typesetting industry. Lorem Ipsum has been "
+ "the industry's standard dummy text ever since the 1500s, when an "
+ "unknown printer took a galley of type and scrambled it to make a type "
+ "specimen book. It has survived not only five centuries, "
+ "but also the leap into electronic typesetting, remaining essentially unchanged.";
JTextArea textAreal = new JTextArea(text);
textAreal.setPreferredSize(new Dimension(300, 150));
textAreal.setLineWrap(true);
textAreal.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textAreal,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}
Resulting in:
In the example, I left the scrolls active for demonstrative purposes only, if you do not want this scrolling to appear without any need, start JScrollPane
by passing only the textarea.
Remembering that JtextArea
, because it is a component that can expand according to its content, should always be passed JScrollPane
, otherwise it will not be able to create scrolls when the text inside it exceeds the area visible.