java如何将命令模式与JavaFX GUI相结合?
我现在的控制器类
public class Controller {
@FXML
public javafx.scene.image.ImageView imageView;
@FXML
private MenuItem openItem;
@FXML
public void openAction(ActionEvent event) {
FileChooser fc = new FileChooser();
File file = fc.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
imageView.setImage(image);
} catch (IOException e) {
System.out.println("lol");
}
}
我怎样才能将openAction函数逻辑放在它自己的类中呢?我需要为我的UI添加大约10-20个带有自己的actionevent侦听器的函数,我不想让所有这些函数都存在于这个控制器类中
# 1 楼答案
不清楚您希望在什么上下文中使用该模式,因此我展示了一个示例转换,它接受窗口的地址(即,将其作为显示的对话框的所有者提交)
它从一个描述命令的接口开始(在本例中,我选择返回
Optional
)下面是抽象类中
Command
接口的实现从现在开始,我们可以通过实现
Command
或扩展AbstractCommand
来实现我们想要的任何功能这是load image命令的一个示例实现
使用命令:
如果希望在不同的控制器中使用openAction,并且不希望创建
Command
的单独实例,请继承Controller