我已经成功地在同一个面板上绘制了两个图表(条形图和折线图).
我正在try 实现一个保存按钮,当单击该按钮时,会将结果图像(带有轴)写入到我保存的 Select 的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();
}
}
}