如何使用 MouseListener 在 Java 中查找 JLabel 数组的 ID 名称
How to find the ID Name of a JLabel Array in Java with MouseListener
我做了什么
我创建了一个这样的 JLabel 数组:
static JLabel numbers[] = new JLabel[25];
我已经给每个 numbers[each of this]
一个 1 到 80 之间的随机数。
我已经为每个 numbers[]
数组添加了一个 MouseListener
。
我想做类似的东西,一旦我按下一个特定的标签来改变自己的背景。但要做到这一点,我必须检测到 JLabel
的 ID 已被按下。
问题:
如何获取JLabel
上被按下的数组的名称或编号?
到目前为止,我只知道如何使用以下代码从中获取文本:
JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
我要numbers[THIS]
的ID,不是文本而是数组的编号。
在 Button 侦听器中,我知道该怎么做,但在 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
附带问题:该数组应该不是静态的,它是静态的表明您的程序存在一些需要修复的设计问题。
我做了什么
我创建了一个这样的 JLabel 数组:
static JLabel numbers[] = new JLabel[25];
我已经给每个 numbers[each of this]
一个 1 到 80 之间的随机数。
我已经为每个 numbers[]
数组添加了一个 MouseListener
。
我想做类似的东西,一旦我按下一个特定的标签来改变自己的背景。但要做到这一点,我必须检测到 JLabel
的 ID 已被按下。
问题:
如何获取JLabel
上被按下的数组的名称或编号?
到目前为止,我只知道如何使用以下代码从中获取文本:
JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
我要numbers[THIS]
的ID,不是文本而是数组的编号。
在 Button 侦听器中,我知道该怎么做,但在 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
附带问题:该数组应该不是静态的,它是静态的表明您的程序存在一些需要修复的设计问题。