- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we implement line wrap and word wrap text inside a JTextArea in Java?
A JTextArea is a multi-line text component to display text or allow the user to enter the text and it will generate a CaretListener interface when we are trying to implement the functionality of the JTextArea component. A JTextArea class inherits the JTextComponent class in Java.
In the below example, we can implement a JTextArea class with a user can select either word wrap or line wrap checkboxes using the ItemListener interface.
Example
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JTextAreaTest { public static void main(String[] args ) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("JTextArea Test"); frame.setSize(350, 275); final JTextArea textArea = new JTextArea(15, 65); frame.add(new JScrollPane(textArea)); final JCheckBox wordWrap = new JCheckBox("word wrap"); wordWrap.setSelected(textArea.getWrapStyleWord()); wordWrap.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent ie) { textArea.setWrapStyleWord(wordWrap.isSelected()); } }); frame.add(wordWrap, BorderLayout.NORTH); final JCheckBox lineWrap = new JCheckBox("line wrap"); lineWrap.setSelected(textArea.getLineWrap()); lineWrap.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent ie) { textArea.setLineWrap(lineWrap.isSelected()); } }); frame.add(lineWrap, BorderLayout.SOUTH ); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); frame.setVisible(true); } }); } }
Output
- Related Articles
- How can we implement the word wrap JTableHeader of a JTable in Java?
- Java Program to set JTextArea to wrap by word in Java
- How to word-wrap text in Tkinter Text?
- How can we display the line numbers inside a JTextArea in Java?
- Word Wrap Problem
- CSS word-wrap property
- Java Program to wrap text in a JTextPane and show Scrollbar
- How to display a bold text inside the JTextArea in Java?\n
- How to wrap the text of a label in JavaFX?
- How to wrap the text in text flow layout in JavaFX?
- How can I append text to JTextArea in Java?
- How can we implement a moving text using a JLabel in Java?
- Wrap Strings of Text in Bootstrap Navbar
- Set the text wrap in a form in HTML
- IntBuffer wrap() method in Java

Advertisements