Search code examples
javaswingjbutton

How to get the indexes of the clicked JButton?


I have a matrix of JButton[][]. I try to add ActionListener to the buttons which stores the index of the button.

I need to make a game.

The first click shows from which button should I step and the second shows where to step.


Solution

  • What you need can be achieved in several ways, using HashMaps, 2D Arrays, etc etc... here is my suggestion:

    Inheritance: you need now a Button with 2 properties that are not defined by default (col and row)

    class MatrixButton extends JButton {
        private static final long serialVersionUID = -8557137756382038055L;
        private final int row;
        private final int col;
    
        public MatrixButton(String t, int col, int row) {
        super(t);
        this.row = row;
        this.col = col;
        }
    
        public int getRow() {
        return row;
        }
    
        public int getCol() {
        return col;
        }
    }
    

    you have for sure a Panel where you can add JButtons, now add instead a MatrixButton

     panel.add(MatrixButton);
    

    then add the actionlistener

    button1.addActionListener(this);
    

    and when you click you get the position coordinates by doing

       @Override
        public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == this.button1) {
            System.out
                .println(((MatrixButton) ae.getSource()).getRow() + "," + ((MatrixButton) ae.getSource()).getCol());
        } else if (ae.getSource() == this.button2) {
            // TODO
        } else if (ae.getSource() == this.button3) {
            // TODO
        }
        }