Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用MouseStener在Java中查找JLabel数组的ID名称_Java_Arrays_Swing_Jlabel_Mouselistener - Fatal编程技术网

如何使用MouseStener在Java中查找JLabel数组的ID名称

如何使用MouseStener在Java中查找JLabel数组的ID名称,java,arrays,swing,jlabel,mouselistener,Java,Arrays,Swing,Jlabel,Mouselistener,我所做的。 我创建了一个JLabel数组,如下所示: static JLabel numbers[] = new JLabel[25]; 我给了每个数字[每个]一个介于1和80之间的随机数 我在每个数字[]数组中添加了一个MouseListener 我想做一些类似的事情,一旦我按下一个特定的标签来改变它自己的背景。但要做到这一点,我必须检测按下JLabel的ID 问题: 如何获取已按下的JLabel上的数组的名称或编号 到目前为止,我只知道如何使用以下代码从中获取文本: JLabel l =

我所做的。

我创建了一个JLabel数组,如下所示:

static JLabel numbers[] = new JLabel[25];
我给了每个
数字[每个]
一个介于1和80之间的随机数

我在每个
数字[]
数组中添加了一个
MouseListener

我想做一些类似的事情,一旦我按下一个特定的标签来改变它自己的背景。但要做到这一点,我必须检测按下
JLabel
的ID

问题:

如何获取已按下的
JLabel
上的数组的名称或编号

到目前为止,我只知道如何使用以下代码从中获取文本:

JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
我想要的是
数字[THIS]
的ID,不是文本而是数组的数字

在Button listener中,我知道如何做到这一点,但在MouseListener中不起作用


(至少使用我尝试过的方法…(
e.getSource().getName();
等)

您已经得到了数组,您已经得到了对按下的JLabel的引用:
e.getSource();
,所以只需在数组中迭代以找到与另一个匹配的数组。例如

@Override
public void mousePressed(MouseEvent e) {
    Object source = e.getSource();
    int index = -1;

    for (int i = 0; i < numbers.length; numbers++) {
        if (numbers[i] == source) {
            index = i;
            break;
        }
    }
}

// here index either == the array item of interest or -1 if no match
@覆盖
公共无效鼠标按下(MouseEvent e){
对象源=e.getSource();
int指数=-1;
对于(int i=0;i

附带问题:该数组应该而不是是静态的,并且它是静态的,这表明您的程序有一些设计问题需要解决。

您是最棒的。非常感谢!我将在5分钟内接受此答案。.由于我的新帐户,我有延迟:)@Erick:不客气。请注意,数组不应该是静态的,最好将其设置为实例数组。