2011-04-23 34 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