JLabel [ ] [ ] 中如何获取鼠标点击标签的索引?

How to get the index of label mouse clicked in JLabel [ ] [ ]?

我有一个 JLabel 组件的二维数组,我想像这样获取鼠标在标签中单击的位置。

Jlabel [x] [y] // I want this x & y

我应该怎么做?

我已经试过了,但我什么也没得到!

new MouseAdapter(){
    public void mousePressed(MouseEvent e){
        int a=e.getX();
        int b=e.getY();
        MainBoard.ML.label=MainBoard.disk1[a][b];
        Color c=MainBoard.ML.label.getForeground();
        if(color==1)
            MainBoard.ML.label.setForeground(Color.black);
        else
            MainBoard.ML.label.setForeground(Color.white);
        new Play(a,b,color);
        new Player2(r);
        MainBoard.disk1[a][b].addMouseListener(new ML1(a,b));
    }
};

我想获取标签数组的 x & y 索引。

用于定位 xy 的未经测试和未编译的代码如下。
请注意,class MouseEvent 的方法 getX() 获取鼠标指针在计算机屏幕上的位置,而不是数组中的 x。对于方法 getY() 也是如此。这就是为什么你一无所获。

在下面的代码中,我将相同的 MouseListener 添加到所有 JLabel

MouseEvent包含鼠标点击的JLabel和classMouseEventreturns的方法getSource()。然后,您需要遍历 JLabel 数组并查看哪个与 MouseEvent 源匹配。

int rows = // number of rows in 2D array
int cols = // number of cols in 2D array
final JLabel[][] labels = new JLabel[rows][cols]
MouseListener ml = new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        Object src = me.getSource();
        int x = -1;
        int y = -1;
        for (int i = 0; i < labels.length(); i++) {
            for (int j = 0; j < labels[i].length; j++) {
                if (src == labels[i][j]) {
                    x = i;
                    y = j;
                    break;
                }
            }
            if (x >= 0) {
                break;
            }
        }
        if (x > 0) {
            System.out.printf("JLabel[%d][%d] was clicked.%n", x, y);
        }
        else {
            System.out.println("Could not find clicked label.");
        }
    }
}
for (int row = 0; row < rows; row++) {
    for (int col = 0; col < cols; col++) {
        labels[row][col] = new JLabel(row + "," + col);
        labels[row][col].addMouseListener(ml);
    }
}