簡體   English   中英

我可以制作一個帶有將要執行的參數的方法嗎

[英]Can i make a method that takes arguments that it will execute

我將重新提出我的問題。

這是我目前擁有的(LWJGL不是JButton):

public static boolean isButtonClicked(String buttonName){
    Button b = getButton(buttonName);
    float mouseY = essentials.Boot.HEIGHT - Mouse.getY() - 1;
    if (Mouse.getX() > b.getX() && Mouse.getX() < b.getX() + b.getWidth() &&
        mouseY > b.getY() && mouseY < b.getY() + b.getHeight()){
        return true;
    }
    return false;
}

那就是我的主要課程

if(Ui.isButtonClicked("buttonName")/*Takes a name of a button as a argument*/){
        System.out.println();
}

所以我不想在我的主體中有幾個if語句。 但是,如果單擊按鈕,它總是與我要執行的操作有所不同。 所以我的問題是,是否有辦法做這樣的事情。 如果您仍然不知道我的意思,我就是要刪除帖子。

您可以使用Interface / Lambda將一個方法傳遞給另一個方法。 例如:

public interface Procedure {
    void act();
}
public void executeCommand(Procedure proc){
    proc.act();
}
//...
// pass a method using lambda expression:
    executeCommand(()->{system.out.println("Hello world"});

//pass a method using traditional way (anonymous class)
    executeCommand(new Procedure() {

        public void act() {
            system.out.println("Hello world");
        }
    });

你的意思是這樣的嗎:

public static void doSmth(String value) {
    System.out.println(value);
 }
//When you call it
doSmth("Hello world");

暫無
暫無

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

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