To wrap the lines of JTextArea
we need to call the setLineWrap(boolean wrap)
method and pass a true
boolean value as the parameter. The setWrapStyleWord(boolean word)
method wrap the lines at word boundaries when we set it to true
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaWrapDemo extends JPanel {
public TextAreaWrapDemo() {
initializeUI();
}
public static void showFrame() {
JPanel panel = new TextAreaWrapDemo();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TextAreaWrapDemo::showFrame);
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
JTextArea textArea = new JTextArea(5, 40);
String text = """
The quick brown fox jumps over the lazy dog. \
The quick brown fox jumps over the lazy dog. \
The quick brown fox jumps over the lazy dog.
""";
textArea.setText(text);
textArea.setFont(new Font("Arial", Font.BOLD, 18));
// Wrap the lines of the JTextArea if it does not fit in the
// current allocated with of the JTextArea.
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
}
}
The output of the code snippet above is:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024