Search code examples
javanetbeansmultiline

Multiline output in Netbeans?


I'm working on a program, with a GUI, that will need to output multiple lines to some kind of TextArea. I tried doing this with a JTextArea, but it turns out that when setting a new text to JTextArea, the old text gets deleted. Is it some kind of way to print multiple lines to a JTextArea? Or should I use an entirely different method/component for displaying text?

I hope this will clarify:

    for (int n = 0; n <= this.length; n++) {
        for (int m = 0; m <= that.length; m++) {
            txtaResult.setText("thisthis is " + n + "\n");

            Random randomGenerator = new Random();
            randomNumber = randomGenerator.nextInt(9)+1;
            txtaResult.setText(thatthat, " + m + ", is " + randomNumber\n");
        }
    }

(txtaResult is a JTextArea) So I want the text in the two txtaResult.setText to stay put in the JTextArea and add onto each other during all iterations.


Solution

  • Just use the append method instead of setText. Everything's behaving exactly as I'd expect it to - I would have been really surprised if setText had appended.

    If you don't want to use append for some reason, you can call getText and concatenate the text yourself:

    txtaResult.setText(textaResult.getText() + "whatever");
    

    ... but using append is cleaner and may be more efficient.

    As an aside, your loop bounds look odd (usually you'd use < rather than <=) and it would be better to create a single instance of Random and call nextInt on it multiple times.