简体   繁体   English

在插入位置的JTextArea中插入文本

[英]Insert text in JTextArea at caret position

I would like to insert text into JTextArea at the current caret position how to do it? 我想在当前插入位置的JTextArea中插入文本怎么做? I have found only java script tutorials. 我只找到了java脚本教程。

Using textarea.setText() ; 使用textarea.setText() ; will replace the whole content of your text. 将取代您文本的全部内容。 Instead of that, you have to use insert() method of your text object. 而不是那样,你必须使用文本对象的insert()方法。

textarea.insert("My String Here", textarea.getCaretPosition());

You can get the caret position by textObject .getCaretPosition() and start adding your text from there. 您可以通过textObject .getCaretPosition()获取插入位置,然后从那里开始添加文本。

I also found this useful: https://stackoverflow.com/a/5255666/2655623 我也发现这很有用: https//stackoverflow.com/a/5255666/2655623

to sum up: 总结一下:

textarea.replaceSelection("");
textarea.insert("My String Here", textarea.getCaretPosition());

Look at the method getCaretPosition() . 看看方法getCaretPosition()

Returns the position of the text insertion caret for the text component. 返回文本组件的文本插入插入符的位置。

使用getDocument().insertString而不是setText方法。

textarea.getDocument().insertString(textarea.getCaretPosition(), t, null);

You can do the following. 您可以执行以下操作。 First set the Caret position and the insert your text. 首先设置Caret位置并插入文本。

textarea.setCaretPosition(int posintion)
textarea.setText(yourData);

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

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