【问题标题】:Can i make a method that takes arguments that it will execute我可以制作一个方法来接受它将执行的参数吗
【发布时间】:2017-06-09 17:38:33
【问题描述】:

我将提出新的问题。

这是我目前拥有的(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();
}

所以我不希望在我的 main 中有几个 if 语句。但是,如果单击按钮,我想要做什么总是不同的。所以我的问题是是否有办法做这样的事情。如果你仍然不明白我的意思,我只是要删除帖子。

【问题讨论】:

  • 请参加 Java 课程或阅读介绍性 Java 编程书籍。
  • 如果您问是否可以对方法进行参数化,那么答案是肯定的……只要您是定义它们的人。
  • 你想要一个方法作为参数?
  • 看起来像 Javascript
  • 这就像将函数作为参数传递给我认为的方法?与 lambda 表达式类似的函数式编程有哪些?

标签: java methods lwjgl


【解决方案1】:

您可以使用 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");
        }
    });

【讨论】:

    【解决方案2】:

    你的意思是这样的吗:

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

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2012-06-14
      • 1970-01-01
      • 2011-09-02
      相关资源
      最近更新 更多