【发布时间】:2021-11-23 23:03:34
【问题描述】:
我正在尝试创建一个带有图标的挥杆棋盘,但我无法使用 HashMap 将图标放到 JButtons 上。 以下是我正在使用的类:
主类
public class GameGUI extends JFrame {
private JButton tiles[][] = new JButton[8][8];
private HashMap<PieceKey, ImageIcon> icons = new HashMap<>();
public GameGUI(){
//swing shenannigans
initImages();
Tile[][] fenTiles = game.getFen().getTiles();
for(int row = 0; row <= 7; row++){
for(int column = 0; column <= 7; column++){
Piece piece = fenTiles[row][column].getPiece();
if(piece != null) {
tiles[row][column].setIcon(icons.get(new PieceKey(piece.getType(), piece.getColor())));
}
}
}
}
public void initImages(){
icons.put(new PieceKey(PieceType.pawn, Team.white), new ImageIcon("pieces/wpawn.png"));
//.....
}
public static void main(String args[]){
GameGUI asd = new GameGUI();
}
}
PieceKey 类
public class PieceKey {
PieceType type; //enum
Team color; //enum
public PieceKey(PieceType type, Team color) {
this.color = color;
this.type = type;
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(!(o instanceof PieceType))
return false;
PieceKey key = (PieceKey) o;
return this.type == key.type && this.color == key.color;
}
@Override
public int hashCode(){
return type.toString().hashCode() * color.toString().length();
}
}
团队枚举
public enum Team {
white, black;
}
PieceType 枚举
public enum PieceType {
pawn, rook, knight, bishop, king, queen;
}
我的问题是每当我打电话时
icons.get(new PieceKey(piece.getType(), piece.getColor()));
它返回null,所以我不能把图标放在按钮上,如果我手动做它工作正常,所以问题出在HashMap上。我试图覆盖 PieceKey 类中的 equals 和 hashcode 函数,但它似乎不起作用。
【问题讨论】:
-
我认为@jccampenero 发现了这个问题。但如果您使用的是最新版本的 Java,您可能需要考虑使用
record代替PieceKey以避免这些问题。 -
这是一个很好的观点@sprinter。