5

我有一个包含 JPanel 的 JScrollPane。我用许多按钮填充这个 JPanel。

是否有可能获得当前显示的按钮?

我知道我可以通过访问 JPanel 的子级,jpanel.getComponents()但这些都是此窗格中的组件;我只想要当前在屏幕上的那些。

4

4 回答 4

8

正如已经对@mKorbel 的回答所评论的那样:

  • 你需要孩子的界限是正确的
  • 您需要将这些界限与“某物”相交是正确的
  • 您需要包含视口(也不是滚动窗格)是错误的

JComponents 有一个 API 可以独立于它们当前显示的方式/位置来获取它们当前可见的部分,因此“某物”是 JComponent 的 visibleRect:

Rectangle visibleRect = myPanel.getVisibleRect();
for (Component child : myPanel.getComponents()) {
   Rectangle childBounds = child.getBounds();
   if (childBounds.intersects(visibleRect)) {
       // do stuff
   }
}
于 2011-12-13T11:37:06.673 回答
7

我假设这个容器已经在屏幕上可见,那么我建议

1)从JScrollPane中提取JViewPort

2)将ChangeListener 添加JViewPort

3)每个可见JComponent(s)返回矩形

4) 并且Rectangle#intersects返回Boolean值是否JComponent(s)可见JViewPort

于 2011-12-13T08:52:02.260 回答
1

询问组件是否可见如何:

for ( Component component : jpanel.getComponents() ) {
    if ( component instanceof JButton && component.isShowing() ) {
        // We've found a button that is showing...
    }
}
于 2011-12-13T08:05:33.490 回答
0
scrollPane.getViewport().getView()
scrollPane.getViewport().getViewRect()
于 2011-12-13T08:41:15.750 回答