简体   繁体   English

向面板添加多个鼠标监听器

[英]Adding more than one mouse listener to a panel

I'm trying to add more than one mouse listener to a panel, but I want them to be on the same line like this: 我正在尝试向面板添加多个鼠标侦听器,但是我希望它们位于同一行:

Paint.paint.addMouseListener(Shape.circle,Shape.blah);

Is that possible? 那可能吗? I know you can do it like this instead: 我知道您可以这样做:

Paint.paint.addMouseListener(Shape.circle);
Paint.paint.addMouseListener(Shape.blah);

And that's not too bad, but I thought it would be easier if you're not using arrays, and you can add it to the same line if it's possible. 并不太糟,但是我认为如果不使用数组会更容易,并且可以将其添加到同一行。 So, anyone know if this is possible? 那么,有人知道这是否可能吗? Thanks. 谢谢。

There is no addMouseListener(...) method that accepts more than one listener, but you can write your own utility method to do so: 没有addMouseListener(...)方法可以接受多个侦听器,但是您可以编写自己的实用程序方法来这样做:

public static void addManyMouseListeners( Component component, MouseListener... mouseListeners ) {

    if ( component != null && mouseListeners != null ) {
        for ( MouseListener mouseListener : mouseListeners ) {
            component.addMouseListener( mouseListener );
        }
    }
}

The varargs parameter allows you to call the method like: varargs参数允许您像这样调用方法:

addManyMouseListeners( Paint.paint, Shape.circle, Shape.blah );

And in fact add as many mouse listeners as you like. 实际上,您可以根据需要添加任意数量的鼠标侦听器。 Inside the method, the varargs parameter is interpreted as an array, and you iterate on it as you would on any array. 在该方法内部,varargs参数被解释为一个数组,您可以像在任何数组上一样对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM