Java 我可以添加一段代码作为方法的参数吗?

Java 我可以添加一段代码作为方法的参数吗?,java,Java,我正在尝试制作一个游戏,这就是我用来在JPanel上绘制GUI的东西 g.drawImage(Assets.help, 950, 650, null); if (mouseManager.getMouseX() >= 950 && mouseManager.getMouseX() <= 982) { if (mouseManager.getMouseY() >= 650 && mouseMa

我正在尝试制作一个游戏,这就是我用来在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";
                    }
                }
            }
g.drawImage(Assets.help,950650,null);

如果(mouseManager.getMouseX()>=950&&mouseManager.getMouseX()=650&&mouseManager.getMouseY()=x1&&mouseManager.getMouseX()=y1&&mouseManager.getMouseY()有多种方法可以实现这一点。在经典Java中,您可以创建自己的侦听器接口并将匿名实例作为参数传递。示例:

//定义自己的侦听器一次(可以添加任意参数)
接口MyListener{
void runAction();
}
//传递侦听器实例
公共虚空绘图按钮(图形g、BuffereImage按钮、BuffereImage按钮按下、int-x1、int-x2、int-y1、int-y2、MyListener侦听器){
g、 drawImage(按钮,x1,y1,空);

如果(mouseManager.getMouseX()>=x1&&mouseManager.getMouseX()=y1&&mouseManager.getMouseY(),则可以使用lambda表达式,或者根据是否需要返回和/或输入(当然,您可以跳过响应并在任何情况下使用函数)

例如

或消费者

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));

您使用的是类
图形
。提示Swing。但您是从头开始使用按钮,而不是使用JButton?@Sterlyn Agnar如果您的问题得到回答,请将相应的答案标记为“接受此答案”;-)
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));