简体   繁体   English

将行的最后一个单词设置为jtextarea中的下一行

[英]Set the last word of the line to the next line in jtextarea

This may be a very simple question but I don't get any answers from anywhere. 这可能是一个非常简单的问题,但我从任何地方都找不到任何答案。

I have a string variable that holds a very long paragraph string, and is intended to be placed on a JTextArea , by .setText(str) ; 我有一个字符串变量,该变量包含一个很长的段落字符串,并打算通过.setText(str)放置在JTextArea

My problem is how to make the last word of the line (that do not fit to the right edge on that line) to be transferred on the next line. 我的问题是如何使该行的最后一个单词(不适合该行的右边缘)在下一行上传输。

An illustration below may help my problem: 下面的插图可能会解决我的问题:

Problem: 问题:

The quick brown fox ju
mps over the lazy dog.

Solution needed: 需要的解决方案:

The quick brown fox
jumps over the lazy
dog.

Enable Word wrapping to force the Text area to not wrap in the middle of a word. 启用自动换行以强制“文本”区域不自动换行。

JTextArea c = new JTextArea();
c.setLineWrap(true);
c.setWrapStyleWord(true);

Source http://www.exampledepot.com/egs/javax.swing.text/ta_Wrap.html 来源http://www.exampledepot.com/egs/javax.swing.text/ta_Wrap.html

The JTextArea has a .setLineWrap property. JTextArea具有.setLineWrap属性。 Sounds like thats what you need. 听起来就是您所需要的。

JTextArea API JTextArea API

Source code from Java2s.com : 来自Java2s.com的源代码:

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

public class MainClass extends JFrame {

  static String sometext = "Text Text Text Text Text Text Text Text Text Text Text ";

  public MainClass() {
    super("Simple SplitPane Frame");
    setSize(450, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JTextArea jt1 = new JTextArea(sometext);
    JTextArea jt2 = new JTextArea(sometext);

    jt1.setLineWrap(true);
    jt2.setLineWrap(true);
    jt1.setMinimumSize(new Dimension(150, 150));
    jt2.setMinimumSize(new Dimension(150, 150));
    jt1.setPreferredSize(new Dimension(250, 200));
    JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jt1, jt2);
    getContentPane().add(sp, BorderLayout.CENTER);
  }

  public static void main(String args[]) {
    MainClass ssb = new MainClass();
    ssb.setVisible(true);
  }
}

You can edit your String data just before setting it to the JTextArea using the below code: 您可以使用以下代码在将字符串数据设置为JTextArea之前编辑它:

    StringBuffer sb=new StringBuffer(str);
sb.setCharAt(str.lastIndexOf(" "), '\n');

Then after set jtextArea.setText(sb.toString()); 然后设置jtextArea.setText(sb.toString());之后

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM