So I have my images stored as ImageIcon's on JButtons. I want the user to click on the JButton of the piece they want to use and then click on another JButton to move it there, how would I do this?
I've tried using an actionListener to get the ImageIcon but its proving very complicated especially because I have an 2d array of JButton Images.
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
JButton[][] squares = new JButton[8][8];
Border emptyBorder = BorderFactory.createEmptyBorder();
for (int row = 0; row < squares.length; row++) {
for (int col = 0; col < squares[row].length; col++) {
JButton tempButton = new JButton();
tempButton.setBorder(emptyBorder);
tempButton.setSize(64, 64);
squares[row][col] = tempButton;
squares[row][col].addActionListener(actionListener);
panel.add(squares[row][col]);
squares[0][0].setIcon(new ImageIcon(BoardGUI.class.getResource("castle.png"), "castle"));
}
}
Try the following code. I don't know the exact code for working with ImageIcons on JButtons, but this gets the ideas across: