我正在创建一个简单的控件来浏览和采样音频文件。我想使用一个ObjectProperty<File>
,以便我可以绑定负责播放文件的按钮的一些属性:
PlayButton.disableProperty.bind(this.BGMFile.isNull());
PlayButton.textProperty.bind(this.BGMFile.asString());
那么我将需要覆盖三件事,其中两件事我已经成功完成,因此不会进入
第三个是 asString 方法:
new SimpleObjectProperty<File>(this, "BGM File", null){
/*yadda yadda overrides*/
@Override public StringBinding asString(){
if (super.get() != null && super.get().exists())
return (StringBinding) Bindings.format(
super.get().getName(), this
);
else return (StringBinding) Bindings.format("[NONE]", this);
}
}
这对我来说是正确的,我什至从 grepCode here中提取了代码,但是当我使用 FileChooser 浏览文件时,我已经设置并选择了我想要使用的文件,然后将其设置为 SimpleProperty 按钮文本保持为[没有任何]。
这是浏览文件的代码:
this.btnBrowseBGM.setOnAction((ActionEvent E) -> {
FileChooser FC = new FileChooser();
FC.getExtensionFilters().add(Filters.AudioExtensions());
FC.setTitle("Browse for Background Audio File");
File F = FC.showOpenDialog(this.getScene().getWindow());
if (F != null && F.exists()) try {
this.BGMFile.set(Files.copy(
F.toPath(),
Paths.get("Settings/Sound/", F.getName()),
StandardCopyOption.REPLACE_EXISTING
).toFile());
} catch(IOException ex) {
Methods.Exception(
"Unable to copy file to Settings Sound Directory.",
"Failed to copy Sound File", ex);
this.BGMFile.set(F);
} else this.BGMFile.set(null);
E.consume();
});
因为路径不存在,所以它对我大喊大叫(这是我的预期),但它仍然应该将BGMFile
属性设置为F
. 我知道它确实如此,因为切换按钮变为活动状态并按下它会播放声音文件。
那么我在这里错过/做错了什么?
编辑:
我想我可能有一个想法:我覆盖的方法之一是 set 方法:
@Override public void set(File newValue){
if (newValue != null && newValue.exists())
super.set(newValue);
else super.set(null);
}
会不会是重写 set 方法导致它不触发被重写的asString
方法?