Reputation: 316
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();
}
Upvotes: 0
Views: 605
Reputation: 718886
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.
Upvotes: 0
Reputation: 347234
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);
}
Upvotes: 1