我正在尝试在JFileChooser
中的文件名后面获取一个自动.png。
我该怎么做?
public class Capture {
public static BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
component.paint(image.getGraphics());
return image;
}
public static void getSaveSnapShot(Component component, String fileName) throws Exception {
BufferedImage img = getScreenShot(component);
JFileChooser jfc = new JFileChooser();
jfc.addChoosableFileFilter(new FileNameExtensionFilter("Image files",new String[] { "png" }));
int retVal = jfc.showSaveDialog(null);
if(retVal==JFileChooser.APPROVE_OPTION) {
File f = jfc.getSelectedFile();
String test = f.getAbsolutePath();
ImageIO.write(img,"png",new File(test));
}
}
}
答案 0 :(得分:1)
只需检查路径是否以png结尾。如果未添加,则:
...
String test = f.getAbsolutePath();
if (!test.endsWith(".png")) {
test = test + ".png";
}
...
答案 1 :(得分:0)
您还可以选择添加过滤器以仅允许某种文件。
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.pdf", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.txt", "txt"));
如果您要确保在手动添加文件类型时没有损坏的文件,这将很有帮助。