【问题标题】:How do I combine the Command Pattern with a JavaFX GUI?如何将命令模式与 JavaFX GUI 结合起来?
【发布时间】:2017-12-02 22:12:12
【问题描述】:

我当前的控制器类

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 侦听器的函数,我不希望所有这些函数都存在于这个控制器类中。

【问题讨论】:

    标签: java oop javafx actionevent


    【解决方案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 来做任何我们想要的实现。

    这是加载图像命令的示例实现

    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

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 2014-08-25
      • 2010-11-18
      • 2018-06-05
      • 2019-12-20
      • 1970-01-01
      • 2011-10-04
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多