java - 我可以将一段代码作为参数添加到方法中吗?
问题描述
我正在尝试制作游戏,这就是我用来在 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
}
}
}
}
解决方案
您可以将 lambda 表达式用作Function、Supplier或Consumer ,具体取决于您是否需要返回和/或输入(当然,您可以跳过响应并在每种情况下使用 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));
推荐阅读
- visual-studio - 是否可以在没有管理员权限的情况下在模拟器中调试 android?
- ios - SwiftUI 中的图像选择器 - 我如何知道用户何时在基于 UIkit 的托管 ViewController 中选择了图像
- java - 在 Android Studio 中更改内容视图的更改样式
- data-science - 为具有多维数据的 K 均值选择质心
- flutter - Base 64 转换后图像未显示
- python-3.x - fasttext 在训练后产生不同的向量
- laravel - Laravel Livewire - 如何强制子组件刷新
- javascript - Angular:如何为文本区域设置条件清除按钮
- python - “......从未等待”错误(Discord-Bot,Python)
- google-sheets - 选择具有非标准月份开始/结束的“纳税月份”