Reputation: 70
I'm working on a program using GridLayout. I have a problem when i try to move a button to another position after action performed. Basically, i have an empty space in the panel with the size of a button. And i want to move the button clicked to this empty space, inversely, the empty space will take the place of this button. I'm using an array to get a model that looks like the frame. So I know where the empty space is in my array (Which is a null value in a JButton Array) and I'm trying to make this button takes the position of the empty space in the array and inversely. But it doesn't really work.
Any help will be appreciated.
private void setGame(int nbLines, int nbRows, int emptyX, int emptyY) {
pane.removeAll();
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (!(j == emptyY && emptyX == i)) {
button = new JButton("A");
model[i][j] = button;
pane.add(model[i][j]);
model[i][j].addActionListener(this);
}
}
}
frame.add(pane);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (e.getSource() == model[i][j]) {
System.out.println("Cordonnées de i : " + i + "Cordonnées de j : " + j);
model[i][j] = null;
setGame(nbLignes, nbCol, i, j);
}
}
}
}
Upvotes: 2
Views: 164
Reputation: 324128
Basically, i have an empty space in the panel with the size of a button.
You can't have an empty space. You need to add an actual component to the panel to fill the space in the GridLayout.
So I would suggest you can do something like:
Container.remove(...)
to remove the button at that cell. Then you use the Container.add(component, index)
method to add a JLabel with no text to fill the empty cell.Container.getCompnent(...)
method until you find the index of the button that was clicked. Upvotes: 2