我正在尝试在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));
    }
  }
}

最佳答案

只需检查路径是否以png结尾。如果没有添加:

...
String test = f.getAbsolutePath();
if (!test.endsWith(".png")) {
    test = test + ".png";
}
...

10-06 08:59
查看更多