我有一个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语句需要在添加新元素类型及其相应的编辑选项时进行更改。那么有什么方法可以做得更好吗?
答案 0 :(得分:2)
我认为如果您的应用程序只有少数(2-4)种不同类型的“事物”由AnchorPane
表示,那么您的方法就完全没问题了。您的方法的替代方案是state pattern。在这种情况下,您当前选择的“项目类型”将是您的州。