views:

195

answers:

3

Hi,

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.

+4  A: 

Sounds like you'll get into a mess of references over there ( at least that's what have happened to me in the past ) .

I would suggest you to have a middle object in charge of those dependencies for you and to move the "business" methods there.

So instead of adding components and losing the references ( or worst, duplicating the references all over the place ) you can use this object which will have the reference:

class AppMediator {
     private JTextArea area;
     private JTabbetPane pane;

     // etc. 

     public void doSomethingWithText() {
          this.area.getText(); // etc 
     }
 }

See the Mediator design pattern. The focus is to move all the "view" objects from where they are ( usually as references in subclasses ) to a common intermediate object.

OscarRyz
+1  A: 

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.

Martijn Courteaux
A: 

I prefer the AppMediator approach but you could also do

scrollPane.getViewport().getView()
anonymous