2017-12-02 73 views
0

我现在控制器类如何将命令模式与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个函数,并且我不希望在这个控制器类中存在所有这些函数。

回答

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