Java:将映像保存到文件目录而不退出应用程序

时间:2017-04-15 14:37:27

标签: java javafx fxml

我是StackOverflow和Java的新手,所以如果不是在正确的地方,如果我对Java概念的理解不对,我会道歉。我在网上看过,但是没有找到问题的解决方案,也不明白为什么会这样。

我正在创建一个应用程序,它截取我的屏幕截图并将其保存到项目的工作源目录中。保存图像后,会打开另一个窗口并显示该图像。

我的问题是保存图像。我可以保存它,但是在我关闭整个程序之前屏幕截图没有出现在项目目录中,因此导致错误,因为尽管文件目录中不存在图像,但第一次无法读取图像它得救了。关闭后,图像显示在目录中,程序运行后应该没有错误,再运行一次。

我不明白为什么会这样。为什么在程序终止之前图像不会出现在文件目录中,我将如何解决此问题?我在 Inteliji Idea 中使用 JavaFx FXML

非常感谢任何帮助。

// This method / function runs on a simple button press.
public void screenshot() throws Exception{


    // Hides the window
    boarderPane.getScene().getWindow().hide();

    String format = "jpg";
    String fileName = "FullScreenshot." + format;

            try {

                // This gives the window enough time to hide so it doesn't get caught in the screenshot
                Thread.sleep(500);


                Robot robot = new Robot();


                Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

                BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
                ImageIO.write(screenFullImage, format, new File("src\\image\\" + fileName));

                System.out.println("A full screenshot saved!");

            } catch (AWTException ex) {
                System.err.println(ex);
            }


    // Creates a new window that will display the screenshot
    Stage imageStage = new Stage();

    Parent newWindow = FXMLLoader.load(getClass().getResource("screenshotWindow.fxml"));
    imageStage.setTitle("Caliber --- Current Screen Shot Window");
    imageStage.setScene(new Scene(newWindow, 800, 800));
    imageStage.show();

    // Saves the screenshot location so it can be used in the other window
    MasterVariables.image = new Image("image\\" + 

1 个答案:

答案 0 :(得分:1)

您需要将您的应用程序视为将在真实用户工作站上运行的内容。

真实用户(即不是你)将没有任何IntelliJ项目。他/她将没有任何src目录。他/她将拥有的是一个只读jar文件,其中包含应用程序的编译类和静态资源,主目录和临时目录。

因此,将图像保存为文件,位于用户主目录中的某个位置或作为临时文件,并使用文件IO (而不是ClassLoader,而不是ClassLoader)从该文件中加载图像访问只读jar文件中的资源)。或者首先避免将其保存到文件中,然后将其存储在内存中。

如果您想知道它不起作用的原因,那是因为您使用ClassLoader加载图像。 ClassLoader可以加载目录下的任何内容或类路径中的jar文件。您的src目录不在类路径中。