管理JavaFX菜单栏的运行时行为
我有一个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-4种)不同类型的“东西”,代表AnchorPane
,那么你的方法就完全没问题。您的方法的替代方法是state pattern。在这种情况下,您当前选择的“项目类型”将是您的状态。
以上是 管理JavaFX菜单栏的运行时行为 的全部内容, 来源链接: utcz.com/qa/262450.html