Java Swing - JList自定义单元格渲染 - 捕获动作

发布于 2024-07-17 03:55:36 字数 133 浏览 3 评论 0原文

每当我为 JList 制作自定义单元格渲染器时,我添加到其中的任何元素都不会响应操作。 例如,如果我让单元格渲染器返回一个带有元素的 JPanel,其中一个元素具有 ActionListener,则它根本不响应。

为什么是这样?

Any time I make a custom cell renderer for a JList, any elements I add to it don't ever respond to actions. For instance, If I have the cell renderer return a JPanel with elements on it, one of which has an ActionListener, it doesn't respond at all.

Why is this?

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

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

发布评论

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

评论(2

十年不长 2024-07-24 03:55:36

渲染器可能看起来像一个返回单元格组件的工厂,但实际上它遵循享元渲染方法,并使用相同组件来渲染所有单元格(每次调用getListCellRendererComponent() 应该为特定单元格重新配置相同的组件实例并返回它,以便可以渲染单元格)。

这样,您就可以让 JList(以及 JTableJTree)显示大量单元格,而无需为每个单元格实例化组件。 作为副作用,渲染组件无法响应事件,因为它仅在渲染循环期间使用,但不会出现在组件树中。

正如 Neil Coffey 所说,您可以将侦听器添加到 JList(JTableJTree)中,并使用辅助方法(>locationToIndex(...)getCellBounds(...)) 来调度受影响的单元格,从而处理单元格特定逻辑。

The renderer may look like a factory for returning components for the cells, but in fact it follows the flyweight rendering approach and uses the same component for rendering all the cells (each call to getListCellRendererComponent() is supposed to reconfigure the same component instance for a specific cell and return it so that cell can be rendered).

That way, you can have JList (as well as JTable and JTree) display massive amount of cells without having to instanciate components for each cell. As a side effect, the render component cannot respond to events, as it is only used during the render loop, but doesn't appear in the component tree.

Just as Neil Coffey said, you can add your listeners to the JList (JTable, JTree) instead, and use the helper methods (locationToIndex(...), getCellBounds(...)) to dispatch which cell was affected and thus deal with cell specific logic.

辞取 2024-07-24 03:55:36

您作为列表单元格渲染器返回的项目正是用于:渲染。 向 JList 注册侦听器(通常,您需要一个 ListSelectionListener)。

The item you return as a list cell renderer is intended for exactly that: rendering. Register listeners with the JList (generally, you'll want a ListSelectionListener).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文