JavaFX FileChooser Filefilter不返回扩展名 [英] JavaFX FileChooser Filefilter not returning extension
问题描述
在我的项目中,我使用JavaFX FileChooser来让用户保存文件.我注意到了一个错误,即带有指定文件过滤器的文件在Linux系统上总是保存为.txt.与Windows不同,我从另一个stackoverflow线程中了解到,在Linux上,fileChooser.showSaveDialog();
返回一个没有所选文件扩展名的文件.我相信,这种不定期的实施有一个非常明显的原因,我不理解.但是我仍然不确定如何适应我的需求.
In my project I use JavaFX FileChooser to let the user save files. I noticed a bug, where a file with a specified file filter would always save as a .txt on Linux systems. From another stackoverflow thread I leaned that unlike Windows, on Linux the fileChooser.showSaveDialog();
returns a file without the chosen file extension. I am confident, that this irregular implementation has a very obvious cause that I am not understanding. But still I am not sure how to adapt this for my needs.
我知道关于类似主题还有其他一些已解决的主题,但是所有解决方案都基于从返回的文件中提取扩展名,在我的情况下,showSaveDialog没有返回扩展名.
I am aware that there are some other solved threads about a similar topic, but all the solutions are based on extracting the extension from the returned file, where in my case there is no extension returned by showSaveDialog.
推荐答案
下面是一个示例,如果用户未使用所选过滤器键入扩展名,则会添加扩展名:
Here is an example that adds an extension if the user didn't type one using their selected filter:
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Save to file.");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
FileChooser fc = new FileChooser();
FileChooser.ExtensionFilter xmlfilter = new FileChooser.ExtensionFilter("XML", "*.xml");
FileChooser.ExtensionFilter mffilter = new FileChooser.ExtensionFilter("mf", "*.mf");
fc.getExtensionFilters().addAll(xmlfilter,mffilter);
fc.setSelectedExtensionFilter(xmlfilter);
File f = fc.showSaveDialog(primaryStage.getOwner());
System.out.println("f = " + f);
if(null == f) {
return;
}
final String selected_description = fc.getSelectedExtensionFilter().getDescription();
System.out.println("selected_description = " + selected_description);
if(selected_description.equals(xmlfilter.getDescription()) && !f.getName().endsWith(".xml")) {
f = new File(f.getParent(),f.getName()+".xml");
} else if(selected_description.equals(mffilter.getDescription()) && !f.getName().endsWith(".mf")) {
f = new File(f.getParent(),f.getName()+".mf");
}
System.out.println("f = " + f);
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Example");
primaryStage.setScene(scene);
primaryStage.show();
}
我在Linux上对其进行了测试,但从未见过它添加.txt.给定的扩展名过滤器可能具有多个扩展名,因此您将不得不选择一个扩展名来任意添加.
I tested it on linux and never saw it add a .txt. A given extension filter might have multiple extensions so you will have to choose one to add arbitrarily.
这篇关于JavaFX FileChooser Filefilter不返回扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!