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 :)
CodePudding user response:
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?
CodePudding user response:
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:
- An integer field allows any value that fits, but there are only a limited set of possibilities. It's misleading for a reader. Strings would have the same problem.
- Since the enumeration is a limited set of possibilities, an IDE can automatically suggest them all when you do want to compare, or otherwise use the values.