我有一个BorderPane,在其上放置了MenuBar。在BorderPane的中心,我根据选择的MenuItem显示不同的AnchorPanes。到目前为止,一切都很好。

现在,如何确定菜单更改行为以响应子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());
}
}


但是,我不确定这是否是最佳解决方案,尤其是考虑到每当我添加新的元素类型及其相应的编辑选项时,都需要更改if / elseif语句。那么,有什么办法可以使我做得更好?

最佳答案

我认为,如果您的应用程序只有少数(2-4)不同类型的“事物”,这些事物由AnchorPane表示,那么您的方法就可以了。您的方法的另一种选择是state pattern。在这种情况下,您当前选择的“项目类型”将是您的状态。

10-08 00:58