2011-04-23 75 views
14

如果在JScrollPane中有JEditorPane,如何从滚动窗格获取编辑器?从JScrollPane获取组件

我试过scrollPane.getComponents()但编辑不在列表中。

回答

28
JViewport viewport = scrollPane.getViewport(); 
JEditorPane editorPane = (JEditorPane)viewport.getView(); 
+1

outch ...即将发布:“自然getViewportView”,但该方法意外不存在,其中一个疯狂的非​​对称;-) – kleopatra 2011-04-24 11:13:07

+0

更短的方式:JEditorPane editorPane =(JEditorPane)scrollPane.getViewport.getView(); – Rubinum 2014-06-23 07:55:42

5

方式一:

JViewport viewport = scrollPane.getViewport(); 
Component[] components = viewport.getComponents(); 

虽然你可能只是有一个拥有引用您的编辑器窗格类领域,并得到更容易的方式。

编辑:按照Jeanette和Rob的说法:获取视口所保持的单个子组件的最佳方法是使用其getView()方法。

我最初的回答使我想起H.L.门肯报价的:

“对于每一个复杂的问题,有一个解决方案,简洁,清晰,简单,和错误的。”

+2

的JViewport最多有一个孩子,它的API由getView访问单个子()(可能返回null如果没有孩子)。所以不赞同@Boro简洁;-) – kleopatra 2011-04-26 22:48:47

+0

@kleopatra:谢谢你和罗布纠正! :) – 2011-04-27 02:28:03

+0

@kleopatra感谢您的更正。好点子。 – Boro 2011-04-27 10:24:45