RSST
RSST

Reputation: 79

Wants to format text in JTextArea

I wants to set the different tab size in text area, line by line. Can anyone give me a solution for it. Is it possible? I wants, after the text typed on text area, when I press format button, wants to add a tab for every line. line 1 - no tab line 2 - 1 tab line 3 - 2 tabs line 4 - 3 tabs

Upvotes: 0

Views: 2298

Answers (3)

Arjun Sol
Arjun Sol

Reputation: 741

Try using setLeftIndent and specify different styles per line.

Here is a Styles example

Upvotes: 1

SnakeDoc
SnakeDoc

Reputation: 14361

I think default tab size/length is OS/system setting dependent. \t I believe does 4 spaces by default on windows....

As far as adding tabs after a new line -- you could do something like:

line.replace("\n", "\n\t");

or

line.replaceAll("\n", "\n\t");

depending on your use-case.

if you need to tab in each time a little further, try something like:

String tabSpacing = "\n\t";
for (int i = 0; i < lines.length; i++) {
    String line = lines[i].replace("\n",tabSpacing);
    tabSpacing += "\t";
}

It's worth mentioning that the newline character differs on some system environments. For example Windows uses crlf (carriage-return, line feed) while the *nix's use just lf (line feed).

So in java you will either use \r\n or just \n depending on the system environment. One way to get around this would be to call the system's property.

System.getProperty("line.separator");

this can be used in conjunction:

final String lineSeparator = System.getProperty("line.separator");
line.replace(lineSeparator, lineSeparator += "\t");

etc...

UPDATE -- Based on a comment from the OP -- you may want to check this SO thread for how to format text into a Java Standard Formatting for Source Code: Java library for code beautify/format

Upvotes: 3

camickr
camickr

Reputation: 324108

Did you read the API? The API has a methods that tell you:

  1. How many lines are in the text area
  2. The starting offset of each line.

I'll let you read the API to find the methods.

You would then create a loop and get the starting offset of each line. Then you use:

textArea.getDocument().insertString(...);

to insert the appropriate number of tabs "\t" for each line.

Upvotes: 3

Related Questions