我基于JavaFX教程创建了这段代码:
final String change[] =
{
"Full Screen", "Exit Full Screen"
};
final MenuItem fullScreen = MenuItemBuilder.create().text(change[0]).build();
fullScreen.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
fullScreen.setText((fullScreen.getText().equals(change[0])) ? change[1] : change[0]);
if (fullScreen.getText().equals(change[0]))
{
primaryStage.setFullScreen(false);
}
else
{
primaryStage.setFullScreen(true);
}
}
});
view.getItems().add(fullScreen);
我需要使用switch语句来改进它,我想在其中设置文本和setFullScreen
。有没有更优雅的方式来实现这个?
编辑:此代码有效,但实现非常难看。
答案 0 :(得分:3)
使用绑定更新文本,您无需关心其他方法更改的初始化和全屏模式
MenuItem fullScreen = new MenuItem();
fullScreen.textProperty().bind(
new When(primaryStage.fullScreenProperty())
.then("Exit Full Screen")
.otherwise("Full Screen"));
fullScreen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
primaryStage.setFullScreen(!primaryStage.isFullScreen());
}
});