有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    不清楚您希望在什么上下文中使用该模式,因此我展示了一个示例转换,它接受窗口的地址(即,将其作为显示的对话框的所有者提交)

    它从一个描述命令的接口开始(在本例中,我选择返回Optional

    public interface Command<R> {
        public Optional<R> execute();
    }
    

    下面是抽象类中Command接口的实现

    public abstract class AbstractCommand<R> implements Command<R> {
    
        private Window window;
    
        public AbstractCommand(Window window) {
            this.window = window;
        }
    
        public Window getWindow() {
            return window;
        }
    }
    

    从现在开始,我们可以通过实现Command或扩展AbstractCommand来实现我们想要的任何功能

    这是load image命令的一个示例实现

    public class LoadImageCommand extends AbstractCommand<Image> {
    
        public LoadImageCommand() {
            this(null);
        }
    
        public LoadImageCommand(Window window) {
            super(window);
        }
    
        @Override
        public Optional<Image> execute() {
            Image image = null;
    
            FileChooser fc = new FileChooser();
            File file = fc.showOpenDialog(getWindow());
            try {
                if(file != null) {
                    BufferedImage bufferedImage = ImageIO.read(file);
                    image = SwingFXUtils.toFXImage(bufferedImage, null);
                }
            } catch (IOException e) {
                System.out.println("lol");
            }
    
            return Optional.ofNullable(image);
        }
    }
    

    使用命令:

    @FXML
    private void openAction(ActionEvent event) {
        new LoadImageCommand().execute().ifPresent(imageView::setImage);
    }
    

    如果希望在不同的控制器中使用openAction,并且不希望创建Command的单独实例,请继承Controller