Search code examples
javaswingjtextarea

Accessing a JTextArea in a JScrollPane


I have a JTextArea in (multiple) JScrollPane in a JTabbedPane.

I need to access the JTextArea. If I didn't have the JScrollPane, I could do:

JTextArea c = (JTextArea)jTabbedPane1.getComponentAt(i);

How would I get it when in a JScrollPane?

Cheers, Gazler.


Solution

  • This line looks complex, but I THINK this would do it.

    JTextArea c = (JTextArea) (((JViewportView) (((JScrollPane) jTabbedPane1.getComponentAt(i)).getViewport()))).getView();
    

    But I think it would be more interesting to store your TextArea's in an ArrayList.
    So you can do this:

    List<JTextArea> listAreas = new ArrayList<JTextArea>();
    
    ...
    JTextArea c = listAreas.get(i);
    

    Create a new one is something like this:

    JTextArea c = new JTextArea();
    jTabbedPane1.addTab("Title", new JScrollPane(c));
    listAreas.add(c);
    

    Hope this helps.