how to remove an action listener?

后端 未结 1 1972
走了就别回头了
走了就别回头了 2021-01-25 13:56

so im making a chess game but only with the knight.

this is the method for moving the knight

public void caballo(final int row, final int column) {

            


        
相关标签:
1条回答
  • 2021-01-25 14:08

    Like nachokk said, you should use: component.removeActionListener(theActionListenerYouWantToRemove)

    Here is how you can use it in your e method:

    public ActionListener e(final int row, final int column,
            final JButton current) {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
    
                current.setIcon(null);
                if (tienebotton(row + 2, column + 1)) {
                    if (e.getSource() == mesa[row + 2][column + 1]) {
                        caballo(row + 2, column + 1);
                    }
                }
                if (tienebotton(row + 2, column - 1)) {
                    if (e.getSource() == mesa[row + 2][column - 1]) {
                        caballo(row + 2, column - 1);
                    }
                }
                if (tienebotton(row - 2, column - 1)) {
                    if (e.getSource() == mesa[row - 2][column - 1]) {
                        caballo(row - 2, column - 1);
                    }
                }
                if (tienebotton(row - 2, column + 1)) {
                    if (e.getSource() == mesa[row - 2][column + 1]) {
                        caballo(row - 2, column + 1);
                    }
                }
    
                if (tienebotton(row + 1, column + 2)) {
                    if (e.getSource() == mesa[row + 1][column + 2]) {
                        caballo(row + 1, column + 2);
                    }
                }
                if (tienebotton(row - 1, column + 2)) {
                    if (e.getSource() == mesa[row - 1][column + 2]) {
                        caballo(row - 1, column + 2);
                    }
                }
                if (tienebotton(row + 1, column - 2)) {
                    if (e.getSource() == mesa[row + 1][column - 2]) {
                        caballo(row + 1, column - 2);
                    }
                }
                if (tienebotton(row - 1, column - 2)) {
                    if (e.getSource() == mesa[row - 1][column - 2]) {
                        caballo(row - 1, column - 2);
                    }
                }
                ((AbstractButton) e.getSource()).setEnabled(false);
                ((AbstractButton) e.getSource()).removeActionListener(this);
            }
        };
    }
    

    I see that you are new to Java, you'll notice that I have slightly modified your e method to only call current.setIcon(null); and ((AbstractButton) e.getSource()).setEnabled(false); I have also made sure that the remove action listener is only called once aswell, you should look to avoid writing duplicate code as much as possible.

    0 讨论(0)
提交回复
热议问题