Java程序,将JTextArea设置为按Java中的单词换行

Java Program to set JTextArea to wrap by word in Java

要将JTextAream设置为按单词换行,您需要使用setWrapStyleWord()。 假设我们创建了一个新的JTextArea并设置了演示文本-

1
2
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!!!!!!!!!!!!!!!!!!!");

现在,按字换行并将其设置为TRUE-

1
textArea.setWrapStyleWord(true)

以下是将JTextArea设置为按单词换行的示例-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 ();
 }
}

输出量