问题
I am trying to make a screen capturing program.
What I have is a transparent window, which will give the area to be captured, with a button capture
on it, and I am trying to instantiate a class captureScreen
that works good when captureScreen
is individually executed using a command prompt
I am trying to instantiate this captureScreen
class when button capture
is hit.
I have tried keeping this class
on my screenrecord.java
, putting the code in event listener
also. In both these cases,I get these errors
AWTException,must be caught or declared
in
Robot robot = new Robot();
and IOException in BufferedImage image
line.
And keeping the captureScreen.java
separate does nothing.System.out.println("Start");
would even not print anything.
Here is my screenrecord.java
code
public class screenrecord extends JFrame implements ActionListener{
public screenrecord() {...
}
public void actionPerformed(ActionEvent e){
if ("record".equals(e.getActionCommand())) {
captureScreen a = new captureScreen();
}
}
}
And captureScreen.java
, works fine individually.
public class captureScreen extends Object{
public static void main(String args[]){
...
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(filename));
System.out.println("Done");
}
}
All your suggestions, comments, advices are welcome and appreciated. Please help me sort this problem. Thanks.
回答1:
You need to be using try/catches. Those aren't errors so much as warnings. For instance, insert this around the code that has the AWTException:
try
{
//code causing AWTException
Robot robot = new Robot();
}
catch(AWTException e)
{
System.out.println("Error"+e);
}
And:
try
{
//code causing IOException
BufferedImage image = robot.createScreenCapture(screenRectangle);
}
catch(IOException e)
{
System.out.println("Error"+e);
}
Or combine both:
try
{
//code causing AWTException or IOException
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
}
catch(IOException e)
{
System.out.println("Error"+e);
}
catch(AWTException e)
{
System.out.println("Error"+e);
}
For further reading, this may help clarify exceptions:
http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
回答2:
Works on editing the captureScreen.java
as,
public class captureScreen extends Object{
public captureScreen() {
....
filename = ".\\out.png";
try{Robot robot = new Robot();
............ }
catch(Exception e) /* Catch Exceptions too */
{
System.out.println("Error"+e);
}
}
public static void main(String args[]){
new captureScreen();
}
}
Use main to instantiate another function.
来源:https://stackoverflow.com/questions/17220399/cannot-instantiate-a-class-using-a-button