2017-05-27 79 views
0

我有一個ListView,並且在用戶更改選擇時偵聽selectedItemProperty。JavaFX撤銷列表視圖選擇

在這個監聽器中,我將一個事件添加到我的UndoManager中。當我嘗試撤銷選擇時,selectedItemProperty觸發ChangeListener,並將其他事件添加到UndoManger並創建一個infinit循環,因爲它會在撤銷某些內容時將一個ListViewSelectionChange添加到UndoManger。

public class DeviceConfigurationController { 

    @FXML private ListView<DeviceConfiguration> device_list; 
    @FXML 
    private void initialize() { 
     device_list.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { 
      UndoManager.add(new ListViewSelectionChange<>(oldValue, device_list)); 
     }); 
    } 

    //redo/undo stuff 
    @FXML 
    private void undo() { 
     UndoManager.undo(); //calls the last Change 
    } 
} 

public class ListViewSelectionChange<T> implements Change { 

    privateT lastValue; 
    private T redoValue; 
    ListView<T> listView; 

    public ListViewSelectionChange(T lastValue, ListView<T> listView) { 
     this.lastValue = lastValue; 
     this.listView = listView; 
    } 

//gets called from the undomanager 
    @Override 
    public void undo() { 
     redoValue = listView.getSelectionModel().getSelectedItem(); 
     listView.getSelectionModel().select(lastValue); //fires the selection listener again, thus adding a ListViewSelection to the UndoManager 
    } 
} 

有人有任何想法如何停止從調用監聽器的列表視圖?

塞巴斯蒂安

回答

1

你可以添加一個簡單的標誌,表示如果監聽器應該被解僱:

public class DeviceConfigurationController { 

    @FXML private ListView<DeviceConfiguration> device_list; 
    private boolean pauseListener; 

    @FXML 
    private void initialize() { 
     device_list.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { 
      if(!pauseListener) 
       UndoManager.add(new ListViewSelectionChange<>(oldValue, device_list)); 
      }    
     }); 
    } 

    @FXML 
    private void undo() { 
     pauseListener = true; 
     UndoManager.undo(); 
     pauseListener = false; 
    } 
} 
+0

我沒有想到這一點。 我添加了一個函數接口,它在un/redo之前和之後被調用。在那裏,我可以修改一個像pauseListener一樣的布爾值。 謝謝 – Frame