
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set JTextArea to Wrap by Word in Java
In this article, we will learn to set a JTextArea in Java to wrap text by word, ensuring that the words in the text fit neatly within the display area rather than breaking in the middle. We will create a simple GUI application using JTextArea and configure it to wrap text by word, so the content is more readable within the bounds of the text area.
Steps to set JTextArea to wrap by word
Following are the steps to set JTextArea to wrap by word ?
- Import the required classes from javax.swing and java.awt for GUI components and layout.
- Create a class named SwingDemo and define a constructor to set up the JTextArea and JFrame.
- In the constructor, create a JFrame as the main window and initialize a JTextArea with sample text to show wrapping.
- Set the line wrap and word wrap style for the JTextArea.
- Add the JTextArea to the JFrame, set the frame's size, layout, and make it visible.
- In the main method, create an instance of SwingDemo to launch the GUI.
Java program to set JTextArea to wrap by word
The following is an example of setting JTextArea to wrap by word using Java ?
package my; import java.awt.GridLayout; import javax.swing.*; public class SwingDemo { SwingDemo() { JFrame frame = new JFrame("Demo"); JTextArea textArea = new JTextArea("This is a text displayed for our example. More content is added in it now. More content is added in it now. We will now wrap this text!!!!!!!!!!!!!!!!!!!"); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); frame.add(textArea); frame.setSize(550,300); frame.setLayout(new GridLayout(2, 2)); frame.setVisible(true); } public static void main(String args[]) { new SwingDemo (); } }
Output
Code explanation
This code sets up a JTextArea that displays a predefined text, configured to wrap by word. We start by creating a JTextArea object and set some text in it. To enable wrapping, textArea.setLineWrap(true); is called, which ensures that the text doesn't extend beyond the JTextArea width. Next, textArea.setWrapStyleWord(true); is used to wrap lines by complete words, maintaining readability. Finally, we add this JTextArea to a JFrame and display it on the screen.