简体   繁体   English

在JScrollPane中访问JTextArea

[英]Accessing a JTextArea in a JScrollPane

I have a JTextArea in (multiple) JScrollPane in a JTabbedPane. 我在JTabbedPane中的(多个)JScrollPane中有一个JTextArea。

I need to access the JTextArea. 我需要访问JTextArea。 If I didn't have the JScrollPane, I could do: 如果没有JScrollPane,则可以执行以下操作:

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

How would I get it when in a JScrollPane? 在JScrollPane中如何获取?

Cheers, Gazler. 干杯,瞪羚。

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. 重点是将所有“视图”对象从它们所在的位置(通常作为子类的引用)移动到一个公共的中间对象。

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 . 但是我认为将TextArea存储在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. 希望这可以帮助。

我更喜欢AppMediator方法,但您也可以这样做

scrollPane.getViewport().getView()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM