简体   繁体   中英

How to move a button after action performed?

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);
            }
        }
    }
}

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:

  1. Add all the button to the GridLayout
  2. Generate a random number to determine which cell should be empty. Save this value as the "empty cell". Then you use the 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.
  3. Then when you click a button you iterate through all the components in the panel using the Container.getCompnent(...) method until you find the index of the button that was clicked.
  4. Now you have two indexes, the empty cell and the clicked cell. Then you use the remove(...) and add(...) methods to swap the two components.
  5. When the swap is finished you update the "empty index" to be the value of the "clicked index".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM