簡體   English   中英

如何在ActionListener中創建類似lambda的模式

[英]How to create a lambda-like pattern in ActionListener

如何從lambda編寫類似這樣的函數:

jButton.addActionListener(ae -> callAnyMethod());

因為我正在創建一個庫,並希望自己實現這樣的模式。 在Java 8和lambda發布之前,有人會如何制作這樣的模式? 就像我想要接近的是:

我試圖將占位符設置為我的CustomButton ActionListener的actionPerformed方法,並調用如下方法:

CustomButton.CustomButtonListener(placeholder method (); ) 

並且用戶只需要創建一個方法並將其寫入磚塊內...例如名為def()的方法:

CustomButton.CustomButtonListener(def());

和def將自動傳遞給我的CustomButtonListener的actionPerformed方法,並將在按鈕單擊時觸發

編輯:

那就是我到目前為止提出的代碼:

ActionListener存儲在我的CustomButton類中作為方法:

public void CustomButtonListener(Object object){

        addActionListener(new ActionListener(){

@Override
        public void actionPerformed(ActionEvent e) {



          // how to call the method stored in the Object "object" here? and actually run it?



            }
    });

和按鈕的代碼片段:

CustomButton button = new CustomButton();

button.CustomButtonListener(def());





public void def(){

    String a = "lambda!";

            System.out.print("a");



}

您必須確定偵聽器使用哪個Interface並聲明匿名類。

讓我們說jButton.addActionListener(...)等待一個ActionListener

jButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        callAnyMethod();
    }
});

Lambdas本身是用Java 8實現的,它是以簡單易讀的方式訪問方法和Functional Interfaces另一種方式。 編譯器會自動檢測它應該使用的內容並調用它。


我不了解您的項目,但如果您能負擔得起,學習如何使用Lambdas(和Streams)將大大提高您的工作效率,使您的代碼更簡單,更易讀,並且更不容易出錯。

Lambda表達式是在Java 8中引入的。如果您使用的是早期Java版本,則可以使用類和接口實現相同的模式。 只需創建一個實現ActionListener接口和相應方法的類。 您可以通過使用匿名類來縮短它。 然后,您可以創建此類的實例並將其傳遞給addActionListener方法。 或多或少,lambdas完全相同(但是,它們可能具有改進的性能)。

這是一個例子:

public static void main() {
    ...
    MyListener myListener = new MyListener();
    jButton.addActionListener(myListener);
    ...
}

public class MyListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Triggered!");
    }
}

並使用匿名類

public static void main() {
    ...
    jButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Triggered!");
        }
    });
    ...
}

如果我沒有誤解你的問題,你的語法已經正確了。

public static void main() {
    ...
    jButton.addActionListener(e -> myListener());
    ...
}
...
public void myListener(){
    dosomething();
}

這是這個的簡寫:

public static void main() {
    ...
    MyListener myListener = new MyListener();
    jButton.addActionListener(myListener);
    ...
}

public class MyListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        dosomething();
    }
}

有關更多信息,請參閱此內容

如需更詳細的explantion你也可以參考這個 ,下λ類型推理部分。

暫無
暫無

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

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