簡體   English   中英

向面板添加多個鼠標監聽器

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

我正在嘗試向面板添加多個鼠標偵聽器,但是我希望它們位於同一行:

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

那可能嗎? 我知道您可以這樣做:

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

並不太糟,但是我認為如果不使用數組會更容易,並且可以將其添加到同一行。 那么,有人知道這是否可能嗎? 謝謝。

沒有addMouseListener(...)方法可以接受多個偵聽器,但是您可以編寫自己的實用程序方法來這樣做:

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

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

varargs參數允許您像這樣調用方法:

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

實際上,您可以根據需要添加任意數量的鼠標偵聽器。 在該方法內部,varargs參數被解釋為一個數組,您可以像在任何數組上一樣對其進行迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM