如何判断哪个项目触发了鼠标收听器
HI all,如何判断哪个项目触发了鼠标收听器
我正在尝试编写一个简单的星级评估组件。我对Java语言相当陌生,我不确定我想要完成的任务甚至可以用Java来完成。是否可以在JLabel数组中添加JLabel,并且数组中的每个JLabel都有一个鼠标事件侦听器。现在是否可以设置它,以便在鼠标事件发生时触发标签[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找到一种方法。
THanks。
而是像你这样使用同一个侦听每个标签:
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
s而不是JLabel
s,因为他们对动作事件有更好的支持。你仍然可以给他们图标。
只要知道JButtons可以看你喜欢的任何方式。他们可以拥有ImageIcons,甚至不需要看起来像按钮。
的方式,我通常做的是:
int i;
for (i = 0; i <max; i++)
if (position[i] == e.getcomponent())
break;
现在position[i]
是你正在寻找的标签。
您可以使用它的setName方法根据其索引命名每个JLabel,然后使用MouseEvent的getComponent方法获取原始JLabel,并使用getName和索引。这将是一种方式,但将涉及将索引信息存储在两个地方(隐式地将其放置在数组中,并显式地作为标签的名称),所以它几乎要求出现不一致。
您也可以通过数组搜索从getComponent获得的JLabel引用,但这并不是那么好,特别是对于大型数组。
为什么指数很重要?您知道如何获取组件,因此只需遍历数组即可获取索引。
注意我想使用按钮,但它看起来很乱,并且很想用ImageIcons找到一种方法。
如何使用按钮解决确定索引的问题?不过,我也同意使用按钮比标签更好,然后使用ActionListener而不是MouseListener。您可以通过使用使按钮看起来像一个标签:
button.setBorderPainted(false);
现在,如果你使用,你可以使用setActionCommand(...)方法来存储按钮的索引值一个ActionListener。然后在使用getActionCommand(...)方法的情况下。
索引重要的原因是因为任何小于等于被点击的索引需要设置为“true”,所以我可以绘制一个填充的开始,并可以返回其他用途的评分。 – user597608 2011-03-20 01:07:53
因此,您可以遍历按钮阵列并为每个按钮设置图标,直至包括点击的按钮。无论如何,你已经得到了如何做到这一点的答案。 – camickr 2011-03-20 02:08:56