java中的PrintScreen只在main时工作?

时间:2014-03-04 10:32:48

标签: java screenshot javax.imageio

我一直在尝试将此代码添加到我的项目中:

public static void Save() throws HeadlessException, AWTException, IOException
{
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension Dim = tk.getScreenSize();
    Rectangle screenRect = new Rectangle(Dim);
    Robot r = new Robot();
    BufferedImage screenCapturedImage = r.createScreenCapture(screenRect);
    DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    Date date = new Date();
    String FileName = dateFormat.format(date);
    ImageIO.write(screenCapturedImage, "png", new File("/home/caio/Desktop/"+FileName+".png"));
}

它给了我这个错误:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: RoboCore.Print.Save
    at Core.Start.main(Start.java:23)
Java Result: 1

我想调用此方法在屏幕上打印结果,但是这段代码不起作用,因为它不是主要方法,对我来说似乎很奇怪......

3 个答案:

答案 0 :(得分:1)

public static void main(String args [])

{

 //remaining code write here;

}

答案 1 :(得分:1)

我尝试编译并运行代码,从main调用代码时没有任何问题:

public static void main(String[] args) {
   try {
      Save();
   } catch (Exception e) {
      // Handle the exception
   }
}

答案 2 :(得分:0)

public static void save() throws AWTException, IOException
{
        Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension Dim = tk.getScreenSize();
    Rectangle screenRect = new Rectangle(Dim);
    Robot r = new Robot();
    BufferedImage screenCapturedImage = r.createScreenCapture(screenRect);
    Format dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
    Date date = new Date();
    String FileName = dateFormat.format(date);

    ImageIO.write(screenCapturedImage, "png", new File("/home/caio/Desktop/" + FileName + ".png"));
    }

尝试一下它对我有用的代码。

您的问题出在ImageIO.write方法中,您添加了“where needededed

所有我改变的是“/home/caio/Desktop/"+FileName+".png”到“/ home / caio / Desktop /”+ FileName +“。png”

和日期格式

然后通过

调用它
public static void main(String[] args)
{
   try
   {
       save();
   }
   catch(Exception e)
   {
       System.out.println(e);
   }
}