Search code examples
javaeclipseswtjfreechartrcp

How to implement a SaveAs Dialog in a JfreeChart SaveAsPNG method


Please, I need your help. Could you tell me how to implement a SWT SaveAs Dialog in the next code? I need that user can choose where he wants to save the chart. Thanks!

 try {
                File file = new File("mychart.png");
                float calidad = 1;

                ChartUtilities.saveChartAsJPEG(file, calidad, chart, 800, 600);
                MessageDialog.openInformation(shell, "Save Chart", "The file has been saved");

            } catch (IOException e1) {
                e1.printStackTrace();
                MessageDialog.openInformation(shell, "Save Chart", "Error saving file. Please try again...");
            }

Solution

  • Use the SWT FileDialog - something like:

    Shell shell = ... current shell
    
    FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
    
    fileDialog.setFilterExtensions(new String [] {"*.png", "*.*"});
    
    fileDialog.setFilterPath(.... any default path you want ....);
    
    String filePath = fileDialog.open();
    
    // TODO check for null 'filePath' - user canceled the save
    
    File file = new File(filePath);
    
    ChartUtilities.saveChartAsPNG(file, calidad, chart, 800, 600);