JavaFX电子表格中的撤消/重做功能

时间:2019-01-17 12:22:07

标签: java javafx spreadsheet scenebuilder

我正在使用Javafx应用程序来处理电子表格视图。我正在从本地存储导入文件,并在javafx应用程序的电子表格视图中显示。我已经实现了几乎所有功能,但是撤消和重做功能对我来说似乎非常困难。即使我也没有从哪里开始,会有什么手术案例,不知道:( 请帮助我,以您的经验和知识。 在此先感谢您!!

1 个答案:

答案 0 :(得分:0)

我已经解决了此问题,此解决方案的逻辑是:-

public class UndoRedo {

    private SpreadsheetCell cell;

    private String oldValue;

    private String newValue;

    public UndoRedo(SpreadsheetCell cell, String oldValue, String newValue) {
        this.cell = cell;
        this.oldValue = oldValue;
        this.newValue = newValue;
    }

    public SpreadsheetCell getCell() {
        return cell;
    }

    public void setCell(SpreadsheetCell cell) {
        this.cell = cell;
    }

    public String getOldValue() {
        return oldValue;
    }

    public void setOldValue(String oldValue) {
        this.oldValue = oldValue;
    }

    public String getNewValue() {
        return newValue;
    }

    public void setNewValue(String newValue) {
        this.newValue = newValue;
    }

}

SpreadSheet上的添加事件,用于在Cell中任何更改操作的列表中添加对象。

mGridBase.addEventHandler(GridChange.GRID_CHANGE_EVENT, (GridChange e) -> {
            isCellEdited = true;
            SpreadsheetCell cell = mGridBase.getRows().get(e.getRow()).get(e.getColumn());
            String oldValue = lastValue;
            UndoRedo undoRedo = new UndoRedo(cell, oldValue, cell.getText());
            undoRedoList.add(undoRedo);
        }); 

现在在

上添加Key事件
  

Ctrl + Z

关于UNDO的最后更改

if (KeyCode.Z == event.getCode() && event.isControlDown()) {
                if (!undoRedoList.isEmpty()) {
                    UndoRedo undoRedo = undoRedoList.remove(undoRedoList.size() - 1);
                    undoRedo.getCell().setItem(undoRedo.getOldValue());
                    mSpreadsheet.getSelectionModel().clearAndSelect(undoRedo.getCell().getRow(), mSpreadsheet.getColumns().get(undoRedo.getCell().getColumn()));
                }
            }

现在,它可以完美,可靠地工作

Grid grid = ...;  Stack<GridChange> undoStack = ...;  grid.addEventHandler(GridChange.GRID_CHANGE_EVENT, new EventHandler<GridChange>() {

         public void handle(GridChange change) {
                 undoStack.push(change);
             }
         });