2014-01-11 21 views
0

我有一個BorderPane,我在其上放置了一個MenuBar。在BorderPane的中心,根據所選的MenuItem,我顯示不同的AnchorPanes。到現在爲止還挺好。管理JavaFX菜單欄的運行時行爲

現在,我如何確保菜單更改行爲以響應在子AnchorPane中選擇的項目?因此,例如,如果用戶選擇「編輯」,會出現根據當前亮顯的項目是否是一個用戶賬號,文件等

到目前爲止,我做東西沿着這些路線不同的動作:

該BorderPane控制器:

public class MenuTest implements Initializable{ 
@FXML 
private BorderPane borderPaneMain; 
@FXML 
private AnchorPane anchorPaneMain; 
@FXML 
private Menu menuEdit; 
@FXML 
private MenuItem itemEdit; 

static String menuMode; 
static String entityName; 

public MenuTest(){ 
    menuMode =""; 
    entityName = ""; 
} 

@Override 
public void initialize(URL arg0, ResourceBundle arg1) { 
    AnchorPane anchor; 
    try { 
     anchor = (AnchorPane) new FXMLLoader().load(getClass().getResource("views/MainView.fxml")); 
     borderPaneMain.setCenter(anchor); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

protected static void setMenuMode(String menuMd, String entityNm){ 
    entityName = entityNm; 
    menuMode = menuMd; 
} 

@FXML 
private void onEditClick(){ 
    if(entityName.equals(AnchorTest.FILE)){ 
     //Launches correct edit view 
     new FXMLLoader().load(getClass().getResource("views/EditFile.fxml")); 
     //Passes the name of the entity so that the controller can retrieve its data 
     FileEditController.setFile(entityName); 
    }else if(entityName.equals(AnchorTest.PERSON)){ 
     new FXMLLoader().load(getClass().getResource("views/EditPerson.fxml")); 
     PersonEditController.setFile(entityName); 
    }     
} 
} 

孩子AnchorPane控制器:

public class AnchorTest implements Initializable{ 

public static final String PERSON = "PERSON"; 
public static final String FILE = "FILE"; 

ObservableList<String> peopleList; 
ObservableList<String> fileList; 

@FXML 
private ListView<String> listPeople; 
@FXML 
private ListView<String> listFiles; 

@Override 
public void initialize(URL location, ResourceBundle resources) { 
    peopleList = FXCollections.observableArrayList("Frank","Matin","Anne"); 
    fileList = FXCollections.observableArrayList("hello.txt","holiday.jpg","cv.doc"); 
    listPeople.setItems(peopleList); 
    listFiles.setItems(fileList); 
} 

@FXML 
private void personSelected(){ 
    MenuTest.setMenuMode(this.PERSON, listPeople.getSelectionModel().getSelectedItem()); 
} 

@FXML 
private void fileSelected(){ 
    MenuTest.setMenuMode(this.FILE, listFiles.getSelectionModel().getSelectedItem()); 
} 
} 

但是我不知道,這是最好的解決方案,尤其是C考慮到if/elseif語句需要在添加新的元素類型及其相應的編輯選項時進行更改。那麼有什麼方法可以做得更好?

回答

2

我想如果你的應用程序只有少數(2-4種)不同類型的「東西」,代表AnchorPane,那麼你的方法就完全沒問題。您的方法的替代方法是state pattern。在這種情況下,您當前選擇的「項目類型」將是您的狀態。