首页 > 解决方案 > 我可以将一段代码作为参数添加到方法中吗?

问题描述

我正在尝试制作游戏,这就是我用来在 JPanel 上绘制 GUI 的方法。

g.drawImage(Assets.help, 950, 650, null);
            if (mouseManager.getMouseX() >= 950 && mouseManager.getMouseX() <= 982) {
                if (mouseManager.getMouseY() >= 650 && mouseManager.getMouseY() <= 682) {
                    g.drawImage(Assets.help_pushed, 950, 650, null);
                    if (mouseManager.isLeftPressed()) {
                        state = "credits";
                    }
                }
            }

它充满了 if 语句并且使我的代码混乱,所以我创建了一个方法来绘制按钮以清理一些空间,但并非所有按钮都会改变状态,所以我想知道是否有办法将代码块作为参数。这是方法:

public void drawButton(Graphics g, BufferedImage button, BufferedImage buttonPushed, int x1, int x2, int y1, int y2, //CODE BLOCK) {
        g.drawImage(button, x1, y1, null);
        if (mouseManager.getMouseX() >= x1 && mouseManager.getMouseX() <= x2) {
            if (mouseManager.getMouseY() >= y1 && mouseManager.getMouseY() <= y2) {
                g.drawImage(buttonPushed, x1, y1, null);
                if (mouseManager.isLeftPressed()) {
                    //CODE BLOCK
                }
            }
        }
    }

标签: java

解决方案


您可以将 lambda 表达式用作FunctionSupplierConsumer ,具体取决于您是否需要返回和/或输入(当然,您可以跳过响应并在每种情况下使用 Function )。

例如

public void drawButton(Graphics g, BufferedImage button, BufferedImage buttonPushed, int x1, int x2, int y1, int y2, //Function<String, String> myFunction / or Supplier<String> mySupplier / or Consumer<String> myConsumer) {
    g.drawImage(button, x1, y1, null);
    if (mouseManager.getMouseX() >= x1 && mouseManager.getMouseX() <= x2) {
        if (mouseManager.getMouseY() >= y1 && mouseManager.getMouseY() <= y2) {
            g.drawImage(buttonPushed, x1, y1, null);
            if (mouseManager.isLeftPressed()) {
                // CODE BLOCK
                // state = myFunction.apply("credits");
                // state = mySupplier.get();
                // myConsumer.accept("credits");
            }
        }
    }
}

函数、供应商和消费者如下所示:

private Function<String, String> myFunction = input -> {
    // I do the processing
    return String.format("Input was: %s", input);
};

private Supplier<String> mySupplier = () -> {
    // I do the processing
    return "Hello World!";
};

private Consumer<String> myConsumer = input -> {
    // I do the processing
    System.out.println(String.format("Input was: %s", input));
};

你也可以像供应商一样使用表达式内联:

drawButton(g,button, buttonPushed, x1, x2, y1, y2, input -> System.out.println(String.format("Input was: %s", input)));

或消费者

drawButton(g,button, buttonPushed, x1, x2, y1, y2, input -> System.out.println(String.format("Input was: %s", input)));

或功能

drawButton(g,button, buttonPushed, x1, x2, y1, y2, input -> String.format("Input was: %s", input));

推荐阅读