java 从 JScrollPane 获取组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5764467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get component from a JScrollPane
提问by Timotheus
If there is a JEditorPane
in a JScrollPane
, how can you get the editor from the scrollpane?
如果 aJEditorPane
中有 a JScrollPane
,您如何从滚动窗格中获取编辑器?
I tried scrollPane.getComponents()
but the editor wasn't in the list.
我试过了,scrollPane.getComponents()
但编辑器不在列表中。
回答by camickr
JViewport viewport = scrollPane.getViewport();
JEditorPane editorPane = (JEditorPane)viewport.getView();
回答by Hovercraft Full Of Eels
One way:
单程:
JViewport viewport = scrollPane.getViewport();
Component[] components = viewport.getComponents();
although you could just have a class field that holds a reference to your editor pane and get it more easily that way.
尽管您可以只拥有一个类字段来保存对编辑器窗格的引用,并通过这种方式更轻松地获取它。
Edit: as per Jeanette and Rob: the best way to get the single child component held by the viewport is with its getView()
method.
编辑:按照 Jeanette 和 Rob 的说法:获得视口持有的单个子组件的最佳方法是使用它的getView()
方法。
My initial answer reminds me of a quote from H.L. Mencken:
我最初的回答让我想起了 HL Mencken 的一句话:
"For every complex problem there is a solution that is concise, clear, simple, and wrong."
“对于每一个复杂的问题,都有一个简洁、清晰、简单和错误的解决方案。”