Search code examples
javaswingarraylistjtextpane

Adding contents of arrayList to a JTextPane document


In my Java program I'm trying to add data from an ArrayList to a JTextPane document. I've tried the following wrapped in a for loop without success:

doc.insertString(doc.getLength(),colorList[j] + "\t", textPane.getStyle("bold"));

I've been looking through the Java Docs for an answer but it's incredibly overwhelming. How I can put information from an ArrayListinto a JTextPane document?


Solution

  • Here is an example of iterating over elements of an ArrayList and inserting them to a JTextPane:

    public class Texting extends JFrame {
    
        Texting() {
    
            List<String> list = new ArrayList<>();
            list.add("AAAAAAA");
            list.add(" ");
            list.add("BBBB");
    
            JTextPane pane = new JTextPane();
            Document doc = pane.getDocument();
            for (String s : list)
                try {
                    doc.insertString(doc.getLength(), s, null);
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
    
            add(pane);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public static void main(String args[]) {
    
            new Texting();
        }
    }