Search code examples
javastringswingjtextareasettext

JTextArea display text and strings


I have a JTextArea and would like to be able to add multiple arguments to like so: messageArea.setText("Hi", name, "how are you today?"); However, I am unable to do so, I do not know how to add multiple arguments to the JTextArea.


Solution

  • The setText() method takes a single String argument, so you have to concatenate the strings, you want to display.

    StringBuilder sb = new StringBuilder();
    sb.append("Hi").append(name).append(", how are you?");
    messageArea.setText(sb.toString());
    

    Other method is to simply use the + operator:

    messageArea.setText("Hi"+name+"...");
    

    Or use the MessageFormat class:

    messageArea.setText(MessageFormat.format("Hi {0} how are you?", name));