Use line wrap in JTextArea that wraps the line to a specific position in JTextArea

纵然是瞬间 提交于 2020-01-06 06:35:09

问题


I have a JTextArea that picks up text from another JTextArea and displays that text as seen in this image:

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);

回答1:


i want it to start from where rahul is written just below that not from left edge of text area

This is not supported in a JTextArea. A JTextArea is used for displaying simple text.

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.

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(...);

So the basic logic would be:

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.



来源:https://stackoverflow.com/questions/51559116/use-line-wrap-in-jtextarea-that-wraps-the-line-to-a-specific-position-in-jtextar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!