我有一个程序可以截取我的图形用户界面的屏幕截图。它会自动将 .gif 文件保存到 eclipse 项目目录中。我想要的是让它询问用户将图像保存在哪里。基本上这样用户就可以浏览文件目录并选择目录。 这是我的代码:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}
最佳答案
我会使用文件选择器对话框而不是 JOptionPane。这是 tutorial 的链接.
例子: 首先,您必须在您的类中声明 JFileChooser 对象并对其进行初始化。
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
现在创建另一个方法:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
此方法返回给您用户选择的绝对路径。 retVal
表示按下了哪个按钮(保存或取消)。如果按下保存,那么您将处理所选文件。
然后你有了这个方法,你可以将它合并到你的代码中。而不是这一行:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
写:
String fileName = getWhereToSave();
关于java - gui截图,选择问题保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4674481/