Search code examples
javaswingjtextarea

How to populate the JTextArea from method with System.out.println()?


I have a problem with JTextArea... I have a method that connect to Database via DB manager and get Hash Table with Result set. After that I printed the values in console. Now I must to change console to JTextArea. This is a method from my class:

public void viewSystemProperties(){

    PropertiesDTO pdto = new PropertiesDTO();
    PropertiesManager pMng = new PropertiesDBmanager();

    pdto.setPropDTO(pMng.getProperties().getPropDTO());
    Iterator<String> it = pdto.getPropDTO().keySet().iterator();

    String key = null, value = null;

    System.out.println("\t\t**************************");
    System.out.println("\t\t*    PROPERTY TABLE:     *");
    System.out.println("\t\t**************************\n");

    while (it.hasNext()){

        key = (String)it.next();
        value = pdto.getPropDTO().get(key);
        System.out.println("  " + key + "\t-------------------\t
                                        ["+value+"]\n");      

    }// while

}// viewSystemProperties()

Instead of System.out.println it must be printed in JTextArea... Thanks for help.


Solution

  • Just create a JTextArea object and use setText(String t) method instead of System.out.println().

    JTextArea textArea = new JTextArea();
    textArea.setText("Mystring");
    

    Here your Mystring can be StringBuilder object's string representation using toString().

    StringBuilder sb = new StringBuilder();
    while (it.hasNext()){
    
    key = (String)it.next();
    value = pdto.getPropDTO().get(key);
    
    sb.append("  " + key + "\t-------------------\t
                                        ["+value+"]\n"); 
    }
    

    Now using setText() method.

    textArea.setText(sb.toString());
    

    JTextArea tutorial Java Swing