获取 JScrollPane 中显示的组件

发布于 2024-12-21 06:57:07 字数 159 浏览 0 评论 0原文

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

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

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

I have a JScrollPane containing a JPanel. I fill this JPanel with many buttons.

Is there any possibility to get the currently shown buttons?

I know I can access the children of a JPanel via jpanel.getComponents() but those are all components in this pane; I want only the ones that are currently on screen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

当梦初醒 2024-12-28 06:57:07

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

  • 您需要子边界
  • 是正确的,您需要将这些边界与“某物”相交是正确的,
  • 错误

您需要包含视口(也不是滚动窗格)的JComponent 有一个 API 可以独立于当前显示方式/位置来获取当前可见部分,因此“某物”是 JComponent 的visibleRect:

Rectangle visibleRect = myPanel.getVisibleRect();
for (Component child : myPanel.getComponents()) {
   Rectangle childBounds = child.getBounds();
   if (childBounds.intersects(visibleRect)) {
       // do stuff
   }
}

As already commented to @mKorbel's answer:

  • it's correct that you need the child bounds
  • it's correct that you need to intersect those bounds with "something"
  • it's wrong that you need the containing viewport (nor the scrollpane)

JComponents have an API to get their currently visible part independently of how/where exactly they are currently shown, so the "something" is the JComponent's visibleRect:

Rectangle visibleRect = myPanel.getVisibleRect();
for (Component child : myPanel.getComponents()) {
   Rectangle childBounds = child.getBounds();
   if (childBounds.intersects(visibleRect)) {
       // do stuff
   }
}
傾城如夢未必闌珊 2024-12-28 06:57:07

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

1) 提取 JViewPort 来自 JScrollPane,

2) addChangeListener 到 JViewPort

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

4) 和 Rectangle#intersects 返回Boolean 值,判断 JComponent(s)JViewPort 中是否可见

I assume that this container is already visible on the screen, then I suggest

1) to extract JViewPort from JScrollPane,

2) addChangeListener to JViewPort

3) each visible JComponent(s) returns Rectangle

4) and Rectangle#intersects returns Boolean value if is JComponent(s) visible or not in JViewPort

空城缀染半城烟沙 2024-12-28 06:57:07

询问组件是否可见如何:

for ( Component component : jpanel.getComponents() ) {
    if ( component instanceof JButton && component.isShowing() ) {
        // We've found a button that is showing...
    }
}

How about asking the components if they're visible:

for ( Component component : jpanel.getComponents() ) {
    if ( component instanceof JButton && component.isShowing() ) {
        // We've found a button that is showing...
    }
}
吃素的狼 2024-12-28 06:57:07
scrollPane.getViewport().getView()
scrollPane.getViewport().getViewRect()
scrollPane.getViewport().getView()
scrollPane.getViewport().getViewRect()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文