如何获取被点击的 JButton 的索引?

How to get the indexes of the clicked JButton?

我有一个 JButton[][] 的矩阵。我尝试将 ActionListener 添加到存储按钮索引的按钮。

我需要做一个游戏。

第一次点击显示我应该从哪个按钮开始,第二次点击显示我应该从哪里开始。

您可以将按钮的文字设置为相关索引:

//while creating the buttons
for(int i = 0; i<buttons.length;i++){
    for(int j = 0; j<buttons[i].length;j++){    
        //create the button
        buttons[i][j] = new JButton((""+i*buttons.length+j));
    }
}

然后你可以查看按钮的索引是什么:

//for the first click
try{
    int from = Integer.parseInt(button.getText());// get the button index as int from the text
}catch(Exception e){
    e.printStackTrace();
}

第二次点击非常相似。

在您的 class 中创建一个接受索引的方法

public void handleClick(int r, int c) { ... }

当您创建按钮时添加一个动作侦听器,它使用正确的索引调用此方法:

import java.util.stream.IntStream;

buttons = new JButton[rowSize][colSize];
IntStream.range(0, rowSize).forEach(r -> {
    IntStream.range(0, colSize).forEach(c -> {
        buttons[r][c] = new JButton(String.format("%d, %d", r, c));
        buttons[r][c].addActionListener(e -> handleClick(r, c));
    });
});

您需要的可以通过多种方式实现,使用 HashMap、2D 数组等...这是我的建议:

继承:您现在需要一个具有 2 个默认情况下未定义的属性(列和行)的按钮

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

你肯定有一个可以添加 JButtons 的面板,现在添加一个 MatrixButton

 panel.add(MatrixButton);

然后添加动作监听器

button1.addActionListener(this);

当您点击时,您可以通过

获得位置坐标
   @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
    }
    }

I try to add ActionListener to the buttons which stores the index of the button.

在这种情况下,您可以简单地获取事件的对象 ActionEvent.getSource() 然后迭代按钮数组直到该对象等于当前索引。实现方法见findButton(Object)

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class ButtonArrayIndices {

    private JComponent ui = null;
    private JButton[][] buttonArray = new JButton[10][5];
    JLabel output = new JLabel("Click a button");

    ButtonArrayIndices() {
        initUI();
    }

    private void findButton(Object c) {
        for (int x = 0; x < buttonArray.length; x++) {
            for (int y = 0; y < buttonArray[0].length; y++) {
                if (c.equals(buttonArray[x][y])) {
                    output.setText(x + "," + y + " clicked");
                    return;
                }
            }
        }
    }

    public void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ActionListener buttonListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                findButton(e.getSource());
            }
        };

        JPanel buttonPanel = new JPanel(new GridLayout(0, 10, 2, 2));
        ui.add(buttonPanel, BorderLayout.CENTER);
        BufferedImage bi = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
        ImageIcon ii = new ImageIcon(bi);
        Insets margin = new Insets(0, 0, 0, 0);
        for (int y = 0; y < buttonArray[0].length; y++) {
            for (int x = 0; x < buttonArray.length; x++) {
                JButton b = new JButton();
                buttonArray[x][y] = b;
                b.setMargin(margin);
                b.setIcon(ii);
                b.addActionListener(buttonListener);
                buttonPanel.add(b);
            }
        }

        output.setFont(output.getFont().deriveFont(20f));
        ui.add(output, BorderLayout.PAGE_END);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ButtonArrayIndices o = new ButtonArrayIndices();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}