JavaFX中Pane快照保存为BMP文件为空的问题求助
JavaFX Pane快照保存为BMP文件为空(0字节)问题
我已在同一个Pane上绘制了BarChart和LineChart两种图表,现在要实现一个保存按钮,点击后把包含坐标轴的图表图像保存为指定BMP文件。代码运行后会弹出成功提示并生成文件,但生成的文件是空的(0字节)。
原代码
@FXML // fx:id="graph" private Pane graph; // Value injected by FXMLLoader @FXML // fx:id="saveButton" private Button saveButton; // Value injected by FXMLLoader // ... @FXML void clickSave(ActionEvent event) { Stage yourStage = (Stage) saveButton.getScene().getWindow(); FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File("Path\\With\\Spaces")); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("BMP Files", "*.bmp")); // Show save dialog File file = fileChooser.showSaveDialog(yourStage); if (file != null) { if (!file.exists()) { try { Files.createFile(file.toPath()); } catch (IOException e) { e.printStackTrace(); // Handle the exception } } WritableImage writableImage = graph.snapshot(new SnapshotParameters(), null); BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage, null); try { ImageIO.write(bufferedImage, "BMP", file); // Inform the user about the successful save Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("File Saved"); alert.setHeaderText(null); alert.setContentText("The file has been saved successfully."); alert.showAndWait(); } catch (IOException e) { e.printStackTrace(); // Inform the user about the error Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("An error occurred while saving the file."); alert.showAndWait(); } } }
修改后的代码(按@James_D建议调整后问题仍存在)
@FXML void clickSave(ActionEvent event) { Stage stage = (Stage) saveButton.getScene().getWindow(); FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File("Path\\With\\Spaces")); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("BMP Files", "*.bmp")); // Show save dialog File file = fileChooser.showSaveDialog(stage); if (file != null) { WritableImage writableImage = graph.snapshot(new SnapshotParameters(), null); BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage, null); try { ImageIO.write(bufferedImage, "BMP", file); if (!file.exists()) { Files.createFile(file.toPath()); } // Inform the user about the successful save Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("File Saved"); alert.setHeaderText(null); alert.setContentText("The file has been saved successfully."); alert.showAndWait(); } catch (IOException e) { e.printStackTrace(); // Inform the user about the error Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("An error occurred while saving the file."); alert.showAndWait(); } } }
内容的提问来源于stack exchange,提问作者MrChickenNuggetBadman
相关产品推荐
相关产品推荐

