Reputation: 29
I was recently working on making a GUI for a tic-tac-toe application with a 3x3 grid of buttons. I do this by using GridBagLayout to add the buttons and then changing their icons to white. The problem arises when I add an ActionListener which sets the clicked button's icon to an 'X' of the same size. Specifically, I can get the icon to change fine, but if I click on a row or column of three buttons then that row or column disappears. I tested this by printing out the sizes of all of the buttons after and found their heights or widths were reduced to 20 or lower, with other buttons dimensions expanding to fill up space.
Window before full row is clicked
Window after full row is clicked
Code for setting initial blank button icon:
while(i < cells.length) {
cells[i].cell = new JButton(new ImageIcon(br.getScaledInstance(100, 100, BufferedImage.SCALE_FAST)));
cells[i].cell.setBorder(BorderFactory.createEmptyBorder());
cells[i].cell.setFocusPainted(false);
if(i < 3) {
cells[i].cell.setBorder(lines);
}
if(i >= 3 && i < 6) {
cells[i].cell.setBorder(line2);
}
if(i >= 6) {
cells[i].cell.setBorder(nat);
}
i++;
}
Code for setting X when clicked:
ActionListener act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton testo = (JButton) e.getSource();
loc = getIndice(testo);
System.out.println("LOC IS: " + loc);
cells[loc].cell.setIcon(new ImageIcon(bro.getScaledInstance(cells[loc].cell.getSize().width, cells[loc].cell.getSize().height , BufferedImage.SCALE_SMOOTH)));
}
};
Any suggestions, solutions, or recommendations would be welcome, thanks!
Upvotes: 0
Views: 484
Reputation: 324147
cells[i].cell = new JButton(new ImageIcon(br.getScaledInstance(100, 100, BufferedImage.SCALE_FAST)));
You don't need to create a separate Icon for every button. You can create the Icon once outside the loop and then use the Icon for every button
When you change the button you use the size of the button. Since your buttons use Borders, you can't use the size of the button as the blank Icon size and "X" icon size will be different. Just use (100, 100) like you do when you create the default Icon. The code would be much simpler:
cells[loc].cell.setIcon(new ImageIcon(bro.getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH)));
Again you don't need to recreate the Icon every time. Just create the Icon once in the constructor of your class.
So create all the Icons at the start and they will all be the same size and you don't have to worry about the component changing size when you switch the Icon.
Also you don't need to update your array containing the button. The ActionEvent gives your the source of the click so you just change the Icon on the button that was clicked.
Upvotes: 1