我正在制作一个纸牌游戏,其中纸牌表示为 JLabel,具有在游戏过程中更改的名称和其他一些属性。我想将相等性定义为简单地比较两张卡片的全名(由字段 fullName
表示)。但是,这给了我一个问题,我不能两次添加同一张卡片(因为我在 Card 类中有其他字段可能不同)。
显然 JPanel 在后台做了一些关于 equals
的检查。然后,我向每张卡片添加一个唯一的 id
字段,并在类里面跟踪我创建了多少张卡片
private static Map<AbstractCard, Integer> idCount = new HashMap<AbstractCard, Integer>();
然后每次调用某个卡片的构造函数时,我都会增加 idCount
中的值。但是,如果我添加对 id
以及原始 name
的检查,不仅 Map 会中断,而且如果名字是平等的。这是该方法现在的样子:
/**
* Compares this card to the specified object. The result is true if and only if
* the argument is not null and is a Card object that represents the same full name
* as this card.
* @return true if the cards are equal, otherwise false
*/
@Override
public boolean equals(Object o)
{
if (!(o instanceof AbstractCard))
return false;
else
{
AbstractCard c = (AbstractCard)o;
return this.fullName.equals(c.fullName) && this.id == c.id;
}
}
关于如何解决这个问题有什么想法吗?
编辑:我的 hashCode
返回 fullName.hashCode()
并且在当前版本中我添加了 id
。
最佳答案
编辑
我做了以下测试,效果很好:
private class MyLabel extends JLabel {
public MyLabel(String text) {
super(text);
}
public boolean equals(Object obj) {
return true;
}
};
public MyPanel() {
getContentPane().setLayout(new GridLayout());
getContentPane().add(new MyLabel("Label 1"));
getContentPane().add(new MyLabel("Label 2"));
getContentPane().add(new MyLabel("Label 3"));
}
你遇到了什么问题?
顺便说一句:这不会解决您的问题,但是 equals
的 JavaDoc 说
Note that it is generally necessary to override the
hashCode
method whenever this method is overridden
如果一张卡片扩展了一个JLabel
,并且您为您拥有的每张卡片都创建了一个实例,那么您根本不需要重写equals
。确保不要将同一张卡添加到两个容器(或两次添加到一个容器)。这也不适用于真实的卡片。
将卡片类与其可视化分开可能是更好的方法。您是否考虑过不将您的卡从 Swing 类延期?
您可以覆盖 toString
并将它们显示在 JList
中。
关于java - 将组件添加到 JPanel 是否存在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2141280/