2017-12-02 109 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