问题描述
我有一个JTextArea
可以从另一个JTextArea
中拾取文本,并显示该文本,如下图所示:
I have a JTextArea
that picks up text from another JTextArea
and displays that text as seen in this image:
我希望JTextArea像上一幅图一样包装rahul的写入行.下面是我较小的JTextArea
中的代码,其中文本显示在较大的JTextArea
中.
I want the JTextArea to wrap the line from where rahul is written as in previous image.And below is the code from my smaller JTextArea
from which the text is shown in the larger JTextArea
.
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
String str=MainFrame.un+" ("+sdf.format(new Date())+") :"+txtSend.getText();
DataServices.send(runm+":"+str); // for sending this to its socket
txtView.append("\n\n\t\t\t\t\t"+str);
txtSend.setText("");
txtSend.requestFocus(true);
推荐答案
JTextArea不支持此功能. JTextArea用于显示简单文本.
This is not supported in a JTextArea. A JTextArea is used for displaying simple text.
您可以使用JTextPane.它允许您控制文本的属性,并且属性之一可以是左缩进.因此,您可以为单行设置段落属性,使其缩进特定数量的像素.
You could use a JTextPane. It allows you to control attributes of the text and one of the attributes could be the left indent. So you can set the paragraph attributes for a single line to be indented by a specific number of pixels.
因此,不必使用制表符对文本进行缩进,而只需在添加文本行时设置左缩进即可.
So instead of using tabs to indent the text you would just need to set the left indent when you add the line of text.
还请注意,JTextPane并未实现append方法,因此您需要通过使用以下命令将文本直接添加到Document中来创建自己的文本:
Note also that a JTextPane does not implement an append method so you would need to create your own by adding text directly to the Document using:
textPane.getDocument.insertString(...);
所以基本逻辑是:
StyledDocument doc=(StyledDocument)textPane.getDocument();
doc.insertString(...);
SimpleAttributeSet attrs = new SimpleAttributeSet();
//StyleConstants.setFirstLineIndent(attrs, 50);
StyleConstants.setLeftIndent(attrs, 50);
doc.setParagraphAttributes(0,doc.getLength(),attrs, false);
这将更改您刚刚添加到文本窗格中的文本行的缩进.
This will change the indent of the line of text you just added to the text pane.
这篇关于在JTextArea中使用换行,将换行包装到JTextArea中的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!