比较图标作为字符串总是返回false?
我目前正在使用Java Swing进行TIC-TAC-TOE游戏,并弄清楚如何创建Checkwin方法。 TIC-TAC-TOE板被初始化为2D按钮。单击时为每个按钮分配一个图像(交替X和O)。 问题是,即使比较两个具有相同字符串描述的图标,也会返回false。这是我的
- 图像分配
public ImageIcon getImage(){
BufferedImage img = null;
String name="";
try{
if(this.num()== 1){
img = ImageIO.read(new FileInputStream(new File("x.jpg")));
name="x";
}else{
img = ImageIO.read(new FileInputStream(new File("o.jpg")));
name="o";
}
}catch(Exception e){
System.out.println(e);
System.out.println("null :(");
return null;
}
Image scaledImage = img.getScaledInstance(40, 40,Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(scaledImage,name);
return imageIcon;
}
的代码,这是平等比较的代码段(我不知道为什么,但是我的2D数组打印出列主要顺序而不是行主要顺序)
buttons[i][j].getIcon().equals(buttons[i-1][j].getIcon()));
这是我第一次发布溢出,请耐心等待我:)
I'm currently working on a Tic-Tac-Toe game with java swing and figuring out how to create a checkWin method. The Tic-Tac-Toe board is initialized as a 2D array of buttons. Each button is assigned an image when clicked (alternating x's and o's).
The problem is, even when comparing two icons with the same string description, it returns false. Here's my code for
- The Image assignment
public ImageIcon getImage(){
BufferedImage img = null;
String name="";
try{
if(this.num()== 1){
img = ImageIO.read(new FileInputStream(new File("x.jpg")));
name="x";
}else{
img = ImageIO.read(new FileInputStream(new File("o.jpg")));
name="o";
}
}catch(Exception e){
System.out.println(e);
System.out.println("null :(");
return null;
}
Image scaledImage = img.getScaledInstance(40, 40,Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(scaledImage,name);
return imageIcon;
}
Here's the code snippet for equality comparison (also I have no idea why, but my 2d array prints out column major order rather than row major order)
buttons[i][j].getIcon().equals(buttons[i-1][j].getIcon()));
comparing the two o's below returns false
This is my first time posting on overflow please be patient with me :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用整数代表“ X和'O”(例如1和0)。然后,将它们显示为屏幕上的图像?
You should use integers instead, to represent 'x's and 'o's(like 1 and 0). And then, show them as images on the screen?
最好使用枚举来比较,而不是像其他人所建议的那样的图标或整数。为什么不整数?因为它们不像枚举中使用常数那样可读 - 您必须记住1或0的含义。还有其他理由也喜欢枚举:
It'd be better to use an enumeration to compare, rather than the icons or integers as others have suggested. Why not integers? Because they're not as readable as using constants from an enumeration - you have to remember what 1 or 0 mean. There are other reasons to prefer an enumeration, too: