大家好,
我正在尝试编写一个简单的星级评定组件。我对 Java 语言相当陌生,我不确定我想要完成的事情是否可以用 Java 完成。我是否可以在 JLabel 数组中添加一个 JLabel,并且数组中的每个 JLabel 都会有一个鼠标事件监听器。现在是否可以对其进行设置,以便当鼠标事件在 Label[3] 上触发时我可以获得它的索引值?
这是我构建面板的方法
public Rating(Integer max,int size) {
JLabel position = new JLabel[max];
this.setLayout(new FlowLayout());
for(int i=0; i != max;i++){
position[i]=new JLabel(icons.getIcon("star-empty", size));
position[i].setOpaque(true);
position[i].addMouseListener(this);
add(position[i]);
}
}
@Override
public void mouseEntered(MouseEvent e) {
JLabel a= (JLabel) e.getComponent();
//****Have some code in here to tell me where in the position array the event came from????***
int index = ?????
}
请提出想法/想法/建议。
注意我想过使用按钮,但它看起来很乱,很想找到一种使用 ImageIcons 的方法。
谢谢。
最佳答案
不像您那样为每个标签使用相同的监听器:
position[i].addMouseListener(this);
...您可以创建一个特殊的监听器类来获取索引号,并允许您稍后找到它:
position[i].addMouseListener(new RatingMouseListener(i));
每个标签都有一个单独的监听器实例,具有不同的索引值。内部类的代码如下所示:
private class RatingMouseListener extends MouseAdapter {
private final int index;
public RatingMouseListener(int index) {
this.index = index;
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered for rating " + index);
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited for rating " + index);
}
}
然后,您只需重写 MouseAdapter 中的任何方法即可。
此外,就像其他人所说的那样,您可能希望使用 JButton
而不是 JLabel
,因为它们对操作事件有更好的支持。您仍然可以给它们提供图标。
关于java - 如何判断哪个项目触发了鼠标监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366035/