fatd
fatd

Reputation: 21

How to set different lines on a JTextPane?

so say I have this JTextPane:

JTextPane list = new JTextPane();
list.setEditable(false);

and I have the following array of strings:

        String[] pop;
        List<String>popp = new ArrayList<>();
        for(String c : Main.population){
            popp.add(c);
        }
        pop = new String[popp.size()];
        int i = 0;
        for(String e : popp){
            pop[i] = e;
            i++;
        }

and I want to display the array of strings on the JTextPane:

  list.setText(pop[0] +  pop[1] + pop[2]);

this will display the strings in a line and when there is no more space in the next line.

How can i make it so every string is in a separate line of the JTextPane?

Upvotes: 2

Views: 505

Answers (4)

Sharcoux
Sharcoux

Reputation: 6085

In Java 8, you can do :

list.setText(String.join("\n",pop));

Upvotes: 0

camickr
camickr

Reputation: 324118

You need to add a newline character between each line:

list.setText(pop[0] + "\n" + pop[1] + "\n" + pop[2]);

Or the better approach is to just update the Document directly:

Document doc = textPane.getDocument();

for (String text: pop)
    doc.insertString(pop[0] + "\n", doc.getLength(), null);

There is no need to create the String containing all the text first. This will take more memory. Adding one line at a time allows you to add any number of lines.

This approach is essentially what the JTextArea.append(...) method does.

Upvotes: 2

Mario Ishac
Mario Ishac

Reputation: 5887

The \n escape character in java would allow you to separate lines. So you could add that character for every element in the array.

 pop[i] = e + "\n";

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347204

You can make use of a StringJoiner set to use \n for new lines, for example

String[] pop = ...;
StringJoiner joiner = new StringJoiner("\n");
for (String text : pop) {
    joiner.add(text);
}

And then just use

list.setText(joiner.toString());

Upvotes: 4

Related Questions