How To Save My Screenshot in java

戏子无情 提交于 2019-12-12 01:16:41

问题


I'm making a program that takes a screenshot and I want to have it so that i have a JButton with an actionlistener that when pressed it saves the image to a certain folder that if does not already exists it makes.

here is what I thought I should do:

@Override
public void actionPerformed(ActionEvent arg0) {
    File dir = new File("C://SnippingTool+/" +  date.getDay());
    dir.mkdirs();
try {
    ImageIO.write(shot, "JPG", dir);
} catch (IOException e) {
    e.printStackTrace();
}

    }

});

I think it has something to do with my File dir = new File and that I am not saving to to the right place.

Here is my Robot taking a screenshot:

try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    } catch (HeadlessException e1) {
        e1.printStackTrace();
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

回答1:


The problem, as I see it is with these two lines...

File dir = new File("C://SnippingTool+/" +  date.getDay());
dir.mkdirs();

This now means that the output you are trying to write to is a directory, when ImageIO is expecting a file, this will fail...

Instead try something like...

File output = new File("C://SnippingTool+/" +  date.getDay() + ".jpg");
File dir = output.getParentFile();
if (dir.exists() || dir.mkdirs()) {
    try {
        ImageIO.write(shot, "JPG", output);
    } catch (IOException e) {
        e.printStackTrace();
    }    
} else {
    System.out.println("Bad Path - " + dir);
}



回答2:


In response to your comment:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at main$2$2.actionPerformed(main.java:148) 

That is at the:

File output = new File(System.getProperty("user.home") + 
                       date.getDay() + ".jpg"); 

(I changed the "C:\" to System.getProperty("User.home")).

There are only two possible causes of an NPE in that line (wrapped for readability):

  • If System.getProperty cannot find the named property, it will return a null. Now the "user.home" property should exist ... but "User.home" almost certainly does NOT exist. (Property names are case sensitive!!)

  • If date is null or date.getDay() returns null. We don't know how you initialized date ... or even what type it is. (Though Date would be a good guess ...)


Both the "user.home" property and the "user.dir" property would work ... though they mean different things.



来源:https://stackoverflow.com/questions/17625976/how-to-save-my-screenshot-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!