如何获取在 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
请注意,类 MouseEvent 的方法 getX() 获取鼠标指针在计算机屏幕上的位置,而不是数组中的 x。方法getY()类似。这就是为什么你一无所获。

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

MouseEvent包含单击鼠标的JLabel,类 MouseEvent 的方法 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);
    }
}

最新更新