Example usage for java.awt FileDialog setFile

List of usage examples for java.awt FileDialog setFile

Introduction

In this page you can find the example usage for java.awt FileDialog setFile.

Prototype

public void setFile(String file) 

Source Link

Document

Sets the selected file for this file dialog window to be the specified file.

Usage

From source file:edu.ku.brc.specify.tasks.services.PickListUtils.java

/**
 * @param localizableIO/* w w  w.j  av a  2s . c  o  m*/
 * @param collection
 * @return
 */
public static boolean importPickLists(final LocalizableIOIFace localizableIO, final Collection collection) {
    // Apply is Import All PickLists

    FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()),
            getResourceString(getI18n("PL_IMPORT")), FileDialog.LOAD);
    dlg.setDirectory(UIRegistry.getUserHomeDir());
    dlg.setFile(getPickListXMLName());
    UIHelper.centerAndShow(dlg);

    String dirStr = dlg.getDirectory();
    String fileName = dlg.getFile();
    if (StringUtils.isEmpty(dirStr) || StringUtils.isEmpty(fileName)) {
        return false;
    }

    final String path = dirStr + fileName;

    File file = new File(path);
    if (!file.exists()) {
        UIRegistry.showLocalizedError(getI18n("PL_FILE_NOT_EXIST"), file.getAbsoluteFile());
        return false;
    }
    List<BldrPickList> bldrPickLists = DataBuilder.getBldrPickLists(null, file);

    Integer cnt = null;
    boolean wasErr = false;

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();
        session.beginTransaction();

        HashMap<String, PickList> plHash = new HashMap<String, PickList>();
        List<PickList> items = getPickLists(localizableIO, true, false);

        for (PickList pl : items) {
            plHash.put(pl.getName(), pl);
            //System.out.println("["+pl.getName()+"]");
        }

        for (BldrPickList bpl : bldrPickLists) {
            PickList pickList = plHash.get(bpl.getName());
            //System.out.println("["+bpl.getName()+"]["+(pickList != null ? pickList.getName() : "null") + "]");
            if (pickList == null) {
                // External PickList is new
                pickList = createPickList(bpl, collection);
                session.saveOrUpdate(pickList);
                if (cnt == null)
                    cnt = 0;
                cnt++;

            } else if (!pickListsEqual(pickList, bpl)) {
                session.delete(pickList);
                collection.getPickLists().remove(pickList);
                pickList = createPickList(bpl, collection);
                session.saveOrUpdate(pickList);
                collection.getPickLists().add(pickList);
                if (cnt == null)
                    cnt = 0;
                cnt++;
            }
        }
        session.commit();

    } catch (Exception ex) {
        wasErr = true;
        if (session != null)
            session.rollback();

        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(PickListEditorDlg.class, ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }

    String key = wasErr ? "PL_ERR_IMP" : cnt != null ? "PL_WASIMPORT" : "PL_MATCHIMP";

    UIRegistry.displayInfoMsgDlgLocalized(getI18n(key), cnt);

    return true;
}

From source file:edu.ku.brc.specify.tasks.services.PickListUtils.java

/**
 * @param localizableIO//from w  ww.  j a  va  2s . co m
 * @param hash HashSet of names of picklists to be pre-selected (can be null)
 */
public static void exportPickList(final LocalizableIOIFace localizableIO, final HashSet<String> hash) {
    // Cancel is Export All PickLists

    List<PickList> items = getPickLists(localizableIO, true, false);
    List<PickList> selectedItems = new ArrayList<PickList>();
    if (hash != null) {
        for (PickList pl : items) {
            if (hash.contains(pl.getName())) {
                selectedItems.add(pl);
            }
        }
    }

    Window window = UIRegistry.getTopWindow();
    boolean isDialog = window instanceof Dialog;

    ToggleButtonChooserDlg<PickList> pickDlg;
    if (isDialog) {
        pickDlg = new ToggleButtonChooserDlg<PickList>((Dialog) window, getI18n("PL_EXPORT"), items);
    } else {
        pickDlg = new ToggleButtonChooserDlg<PickList>((JFrame) window, getI18n("PL_EXPORT"), items);
    }

    pickDlg.setUseScrollPane(true);
    pickDlg.setAddSelectAll(true);
    pickDlg.createUI();
    pickDlg.setSelectedObjects(selectedItems);
    UIHelper.centerAndShow(pickDlg);

    Integer cnt = null;
    if (!pickDlg.isCancelled()) {
        items = pickDlg.getSelectedObjects();

        String dlgTitle = getResourceString(getI18n("RIE_ExportResource"));

        FileDialog dlg;
        if (isDialog) {
            dlg = new FileDialog((Dialog) window, dlgTitle, FileDialog.SAVE);
        } else {
            dlg = new FileDialog((Frame) window, dlgTitle, FileDialog.SAVE);
        }
        dlg.setDirectory(UIRegistry.getUserHomeDir());
        dlg.setFile(getPickListXMLName());

        UIHelper.centerAndShow(dlg);

        String dirStr = dlg.getDirectory();
        String fileName = dlg.getFile();

        if (StringUtils.isNotEmpty(dirStr) && StringUtils.isNotEmpty(fileName)) {
            String ext = FilenameUtils.getExtension(fileName);
            if (StringUtils.isEmpty(ext) || !ext.equalsIgnoreCase("xml")) {
                fileName += ".xml";
            }

            try {
                File xmlFile = new File(dirStr + File.separator + fileName);

                ArrayList<BldrPickList> bldrPickLists = new ArrayList<BldrPickList>();
                for (PickList pl : items) {
                    bldrPickLists.add(new BldrPickList(pl));
                }
                DataBuilder.writePickListsAsXML(xmlFile, bldrPickLists);
                cnt = bldrPickLists.size();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            UIRegistry.displayInfoMsgDlgLocalized(getI18n(cnt != null ? "PL_WASEXPORT" : "PL_ERR_IMP"), cnt);
        }
    }
}

From source file:ec.display.chart.StatisticsChartPaneTab.java

/**
 * This method initializes jButton  /* w w w.  j  a  v  a  2s  . c  om*/
 *  
 * @return javax.swing.JButton      
 */
private JButton getPrintButton() {
    if (printButton == null) {
        printButton = new JButton();
        printButton.setText("Export to PDF...");
        final JFreeChart chart = chartPane.getChart();
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try

                {
                    int width = chartPane.getWidth();
                    int height = chartPane.getHeight();

                    FileDialog fileDialog = new FileDialog(new Frame(), "Export...", FileDialog.SAVE);
                    fileDialog.setDirectory(System.getProperty("user.dir"));
                    fileDialog.setFile("*.pdf");
                    fileDialog.setVisible(true);
                    String fileName = fileDialog.getFile();
                    if (fileName != null)

                    {
                        if (!fileName.endsWith(".pdf")) {
                            fileName = fileName + ".pdf";
                        }
                        File f = new File(fileDialog.getDirectory(), fileName);
                        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
                        document.addAuthor("ECJ Console");
                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(width, height);
                        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
                        chart.draw(g2, rectangle2D);
                        g2.dispose();
                        cb.addTemplate(tp, 0, 0);
                        document.close();
                    }
                } catch (Exception ex)

                {
                    ex.printStackTrace();
                }
            }
        });
    }
    return printButton;
}

From source file:Forms.CreateGearForm.java

private GearSpec loadGearSpec() {
    //Get top level frame
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(MasterPanel);

    //Create dialog for choosing gearspec file
    FileDialog fd = new FileDialog(topFrame, "Choose a .gearspec file", FileDialog.LOAD);
    fd.setDirectory(System.getProperty("user.home"));
    fd.setFile("*.gearspec");
    fd.setVisible(true);/*from w  w  w .ja v a2  s. c o m*/
    //Get file
    String filename = fd.getFile();
    if (filename == null)
        System.out.println("You cancelled the choice");
    else {
        System.out.println("You chose " + filename);

        //Get spec file
        File specFile = new File(fd.getDirectory() + Utils.pathSeparator() + filename);

        //If it exists, set it as the selected file path
        if (specFile.exists()) {
            //Generate spec
            return Utils.specForFile(specFile);
        }
    }

    return null;
}

From source file:com.awesheet.models.Workbook.java

@Override
public void onMessage(final UIMessage message) {
    switch (message.getType()) {
    case UIMessageType.CREATE_SHEET: {
        addSheet(new Sheet(this, "Sheet " + (newSheetID + 1)));
        break;//w w  w .  j  a  v a2  s. co m
    }

    case UIMessageType.SELECT_SHEET: {
        SelectSheetMessage uiMessage = (SelectSheetMessage) message;
        selectSheet(uiMessage.getSheet());
        break;
    }

    case UIMessageType.DELETE_SHEET: {
        DeleteSheetMessage uiMessage = (DeleteSheetMessage) message;
        removeSheet(uiMessage.getSheet());
        break;
    }

    case UIMessageType.CREATE_BAR_CHART: {
        CreateBarChartMessage uiMessage = (CreateBarChartMessage) message;

        // Get selected cells.
        Cell selectedCells[] = getSelectedSheet().collectSelectedCells();

        BarChart chart = new BarChart(selectedCells);
        chart.setNameX(uiMessage.getXaxis());
        chart.setNameY(uiMessage.getYaxis());
        chart.setTitle(uiMessage.getTitle());

        if (!chart.generateImageData()) {
            UIMessageManager.getInstance().dispatchAction(
                    new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP, new MessagePopup("Error",
                            "Could not create a chart. Please make sure the cells you selected are in the correct format.")));
            break;
        }

        UIMessageManager.getInstance()
                .dispatchAction(new ShowPopupAction<ChartPopup>(UIPopupType.VIEW_CHART_POPUP,
                        new ChartPopup(new Base64().encodeAsString(chart.getImageData()))));

        break;
    }

    case UIMessageType.CREATE_LINE_CHART: {
        CreateLineChartMessage uiMessage = (CreateLineChartMessage) message;

        // Get selected cells.
        Cell selectedCells[] = getSelectedSheet().collectSelectedCells();

        LineChart chart = new LineChart(selectedCells);
        chart.setNameX(uiMessage.getXaxis());
        chart.setNameY(uiMessage.getYaxis());
        chart.setTitle(uiMessage.getTitle());

        if (!chart.generateImageData()) {
            UIMessageManager.getInstance().dispatchAction(
                    new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP, new MessagePopup("Error",
                            "Could not create a chart. Please make sure the cells you selected are in the correct format.")));
            break;
        }

        UIMessageManager.getInstance()
                .dispatchAction(new ShowPopupAction<ChartPopup>(UIPopupType.VIEW_CHART_POPUP,
                        new ChartPopup(new Base64().encodeAsString(chart.getImageData()))));

        break;
    }

    case UIMessageType.SAVE_CHART_IMAGE: {
        final SaveChartImageMessage uiMessage = (SaveChartImageMessage) message;

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                byte imageData[] = new Base64().decode(uiMessage.getImageData());

                FileDialog dialog = new FileDialog(MainFrame.getInstance(), "Save Chart Image",
                        FileDialog.SAVE);
                dialog.setFile("*.png");
                dialog.setVisible(true);
                dialog.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return (dir.isFile() && name.endsWith(".png"));
                    }
                });

                String filePath = dialog.getFile();
                String directory = dialog.getDirectory();
                dialog.dispose();

                if (directory != null && filePath != null) {
                    String absolutePath = new File(directory + filePath).getAbsolutePath();

                    if (!FileManager.getInstance().saveFile(absolutePath, imageData)) {
                        UIMessageManager.getInstance()
                                .dispatchAction(new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP,
                                        new MessagePopup("Error", "Could not save chart image.")));
                    }
                }
            }
        });

        break;
    }
    }
}

From source file:Forms.CreateGearForm.java

private Boolean saveSpec(GearSpec spec) {

    //Get top level frame
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(MasterPanel);

    //Create dialog for choosing gearspec file
    FileDialog fd = new FileDialog(topFrame, "Save .gearspec file", FileDialog.SAVE);
    fd.setDirectory(System.getProperty("user.home"));
    // Gets the name that is specified for the spec in the beginning
    fd.setFile(spec.getName() + ".gearspec");
    fd.setVisible(true);//from  w w w  .  j  a v  a2 s.co m
    //Get file
    String filename = fd.getFile();
    if (filename == null) {
        System.out.println("You cancelled the choice");
        return false;
    } else {
        System.out.println("You chose " + filename);

        //Get spec file
        File specFile = new File(fd.getDirectory() + Utils.pathSeparator() + filename);

        //Serialize spec to string
        String gearString = gson.toJson(spec);

        try {
            //If it exists, set it as the selected file path
            if (specFile.exists()) {
                FileUtils.forceDelete(specFile);
            }

            //Write new spec
            FileUtils.write(specFile, gearString);
        } catch (IOException e) {
            e.printStackTrace();
            showSaveErrorDialog();
            return false;
        }

        return true;
    }
}

From source file:jpad.MainEditor.java

public void saveAs_OSX_Nix() {
    String fileToSaveTo = null;/*  www.ja v a2 s  .com*/
    FilenameFilter awtFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".txt")) {
                return true;
            } else {
                return false;
            }
        }
    };
    FileDialog fd = new FileDialog(this, "Save Text File", FileDialog.SAVE);
    fd.setDirectory(System.getProperty("java.home"));
    if (curFile == null)
        fd.setFile("Untitled.txt");
    else
        fd.setFile(curFile);
    fd.setFilenameFilter(awtFilter);
    fd.setVisible(true);
    if (fd.getFile() != null)
        fileToSaveTo = fd.getDirectory() + fd.getFile();
    else {
        fileToSaveTo = fd.getFile();
        return;
    }

    curFile = fileToSaveTo;
    JRootPane root = this.getRootPane();
    root.putClientProperty("Window.documentFile", new File(curFile));
    hasChanges = false;
    hasSavedToFile = true;
}

From source file:JDAC.JDAC.java

public void saveData() {
    DateFormat df = new SimpleDateFormat("ddmmyy_HHmm");

    FileDialog fd = new FileDialog(this, "Export as...", FileDialog.SAVE);

    fd.setFile("Data_" + df.format(new Date()) + ".csv");
    fd.setVisible(true);//from   ww  w. j a  va2 s. c  o m

    if (fd.getFile() == null) {
        setStatus("Export CSV canceled");
        //export canceled
        return;
    }

    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(fd.getDirectory() + fd.getFile()));
        out.write(dataToCSVstring());
        out.close();
        setStatus("Export CSV successful");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "" + "Error while exporting data...\n"
                + "If the error persists please contact the system administrator");
        return;
    }
}

From source file:JDAC.JDAC.java

public void exportPNG() {
    DateFormat df = new SimpleDateFormat("ddmmyy_HHmm");

    FileDialog fd = new FileDialog(this, "Export as...", FileDialog.SAVE);

    fd.setFile("Chart_" + df.format(new Date()) + ".png");
    fd.setVisible(true);/*from ww  w  .  j a  v  a2  s . com*/

    if (fd.getFile() == null) {
        setStatus("Export PNG canceled");
        //export canceled
        return;
    }

    mChart.setTitle(currentSensor);

    try {
        ChartUtilities.saveChartAsPNG(new File(fd.getDirectory() + fd.getFile()), mChart,
                Definitions.exportPNGwidth, Definitions.exportPNGheight);
        setStatus("Export PNG successful");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "" + "Error while exporting chart...\n"
                + "If the error persists please contact the system administrator");
        mChart.setTitle(mainChartPreviewTitle);
        return;
    }

    mChart.setTitle(mainChartPreviewTitle);
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Persists out the timelord file and allows the user to choose where
 * the file should go.//from   w ww . j  av a  2s  .  c  om
 *
 * @param rwClassName the name of the RW class
 *        (e.g. "net.chaosserver.timelord.data.ExcelDataReaderWriter")
 * @param userSelect allows the user to select where the file should
 *        be persisted.
 */
public void writeTimeTrackData(String rwClassName, boolean userSelect) {
    try {
        Class<?> rwClass = Class.forName(rwClassName);
        TimelordDataReaderWriter timelordDataRW = (TimelordDataReaderWriter) rwClass.newInstance();

        int result = JFileChooser.APPROVE_OPTION;
        File outputFile = timelordDataRW.getDefaultOutputFile();

        if (timelordDataRW instanceof TimelordDataReaderWriterUI) {
            TimelordDataReaderWriterUI timelordDataReaderWriterUI = (TimelordDataReaderWriterUI) timelordDataRW;

            timelordDataReaderWriterUI.setParentFrame(applicationFrame);
            JDialog configDialog = timelordDataReaderWriterUI.getConfigDialog();

            configDialog.pack();
            configDialog.setLocationRelativeTo(applicationFrame);
            configDialog.setVisible(true);
        }

        if (userSelect) {
            if (OsUtil.isMac()) {
                FileDialog fileDialog = new FileDialog(applicationFrame, "Select File", FileDialog.SAVE);

                fileDialog.setDirectory(outputFile.getParent());
                fileDialog.setFile(outputFile.getName());
                fileDialog.setVisible(true);
                if (fileDialog.getFile() != null) {
                    outputFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
                }

            } else {
                JFileChooser fileChooser = new JFileChooser(outputFile.getParentFile());

                fileChooser.setSelectedFile(outputFile);
                fileChooser.setFileFilter(timelordDataRW.getFileFilter());
                result = fileChooser.showSaveDialog(applicationFrame);

                if (result == JFileChooser.APPROVE_OPTION) {
                    outputFile = fileChooser.getSelectedFile();
                }
            }
        }

        if (result == JFileChooser.APPROVE_OPTION) {
            timelordDataRW.writeTimelordData(getTimelordData(), outputFile);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(applicationFrame,
                "Error writing to file.\n" + "Do you have the output file open?", "Save Error",
                JOptionPane.ERROR_MESSAGE, applicationIcon);

        if (log.isErrorEnabled()) {
            log.error("Error persisting file", e);
        }
    }
}