检查 CardLayout 中是否存在带有名称的卡片 [英] Check if a card with a name is present in a CardLayout

查看:33
本文介绍了检查 CardLayout 中是否存在带有名称的卡片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CardLayout,我只在需要时在其中添加卡片.因此,当需要显示特定卡片(由其名称标识)时,我需要一种方法来检查具有该名称的卡片是否已经存在,以便我可以相应地显示或创建它.

I have a CardLayout in which I add cards only as needed. So, when the need arises to show a particular card (identifed by its name), I need a way to check if a card with that name is already present, so that I can either show or create it accordingly.

根据CardLayout 文档

使用 addLayoutComponent 翻转到以指定名称添加到此布局的组件.如果不存在这样的组件,那么什么都不会发生.

Flips to the component that was added to this layout with the specified name, using addLayoutComponent. If no such component exists, then nothing happens.

因此,如果我要求它显示尚未添加的卡片,则不会引发任何错误.我找不到任何可以让我检查卡片是否存在的 API.

So, no error will be thrown if I ask it to show a card that hasn't been added yet. I couldn't find any API that would let me check if a card is present.

那么,这可能吗?如果不是,人们将如何解决这个问题?有一个解决方案,我手动记住我添加了哪些卡片,但感觉 Swing 应该能够处理这个问题.

So, is this possible to do? If not how would one go about addressing this? There is the solution that I manually remember what cards I have added but it feels swing should be able to handle this.

推荐答案

CardLayout API 无法检查组件是否已添加给定名称.

CardLayout API provides no way to check if a component has already been added with a given name.

如果您真的想这样做(但我强烈建议反对这样做),那么您可以在 CardLayout 上使用 reflection容器使用,并读取其 vector 字段,然后检查每个条目(CardLayout$Card 类型)的给定名称.如您所见,这看起来像是一个 hack,如果有一天 CardLayout 被重构,它可能会崩溃(当前的实现非常丑陋).

If you really want to do that (but I would strongly advise AGAINST doing that), then you could use reflection on the CardLayout used by the container, and read its vector field, then check each entry (of type CardLayout$Card) for the given name. As you see, that looks like a hack and it could break if CardLayout was refactored some day (current implementation is quite ugly).

最好的方法是直接跟踪 Set 字段中所有添加的孩子的名字.无论如何,这真的没什么大不了的.

The best way would be for you to directly keep track of the names of all added children in a Set<String> field somewhere. And this is really not a big deal to do that anyway.

这篇关于检查 CardLayout 中是否存在带有名称的卡片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆