Example usage for javax.swing JFileChooser setFileFilter

List of usage examples for javax.swing JFileChooser setFileFilter

Introduction

In this page you can find the example usage for javax.swing JFileChooser setFileFilter.

Prototype

@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.")
public void setFileFilter(FileFilter filter) 

Source Link

Document

Sets the current file filter.

Usage

From source file:com.igormaznitsa.jhexed.swing.editor.ui.MainForm.java

private void menuFileExportAsJavaConstantsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileExportAsJavaConstantsActionPerformed
    SelectLayersExportData toExport = prepareExportData();

    final DialogSelectLayersForExport dlg = new DialogSelectLayersForExport(this, false, false, false,
            toExport);/*from  w  w w .  ja v  a 2  s  . co  m*/
    dlg.setTitle("Select data to export as Java constants");
    dlg.setVisible(true);
    toExport = dlg.getResult();
    if (toExport != null) {
        final JFileChooser fileChooser = new JFileChooser(this.lastExportedFile);
        fileChooser.setFileFilter(Utils.JAVA_FILE_FILTER);
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            this.lastExportedFile = ensureFileExtenstion(fileChooser.getSelectedFile(), "java");
            processExporterAsLongTask(this, "Export to Java source file",
                    new JavaConstantExporter(getDocumentOptions(), toExport, this.cellComments),
                    this.lastExportedFile);
        }
    }
}

From source file:cn.labthink.ReadAccess060.java

private void jButton_exportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_exportActionPerformed
    JFileChooser jfc = new JFileChooser();
    ExtensionFileFilter filter;//from  w  ww . j  av  a 2 s .  c om

    if (jTable1.getSelectedRowCount() == 1) {
        // filter
        filter = new ExtensionFileFilter("xls", false, true);
        filter.setDescription("Save Export File");

        jfc.setDialogTitle("Create the Export Excel file");
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    } else if (jTable1.getSelectedRowCount() > 1) {
        // filter
        filter = new ExtensionFileFilter("", false, true);
        filter.setDescription("Save Export Files");
        jfc.setDialogTitle("Choose the Export Directory");
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    } else {
        //?
        jLabel_info.setText("<html><font color='red'>No Record Selected</font></html>");
        return;
    }

    //?
    FileSystemView fsv = FileSystemView.getFileSystemView();
    //?
    jfc.setCurrentDirectory(fsv.getHomeDirectory());

    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.SAVE_DIALOG);

    jfc.setFileFilter(filter);
    int result = jfc.showSaveDialog(this); // ""?

    if (result == JFileChooser.APPROVE_OPTION) {
        if (jTable1.getSelectedRowCount() == 1) {
            //
            String filesrc = jfc.getSelectedFile().getAbsolutePath();
            if (!filesrc.toLowerCase().endsWith(".xls")) {
                filesrc = jfc.getSelectedFile().getAbsolutePath() + ".xls";
            }
            outputfile = new File(filesrc);
            jLabel_info.setText("Exported File:" + outputfile.getAbsolutePath());
        } else if (jTable1.getSelectedRowCount() > 1) {
            //
            outputfile = jfc.getSelectedFile().isDirectory() ? jfc.getSelectedFile()
                    : jfc.getSelectedFile().getParentFile();
            if (outputfile == null) {
                outputfile = fsv.getHomeDirectory();
            }
            jLabel_info.setText("Exported to path:" + outputfile.getAbsolutePath());
        } else {
            //?
            return;
        }

    } else {
        return;
    }

    if (inputfile == null) {
        return;
    }

    int[] rows = jTable1.getSelectedRows();
    if (rows.length == 1) {
        //?
        book = null;
        ExportOneRecord(rows[0]);
    } else {
        File path = outputfile;

        for (int rowindex = 0; rowindex < rows.length; rowindex++) {
            int k = rows[rowindex];
            book = null;
            outputfile = new File(path.getAbsolutePath() + "/" + jTable1.getValueAt(k, 0) + ".xls");
            ExportOneRecord(k);
        }
    }
    //        int k = jTable1.getSelectedRow();
    //        ExportOneRecord(k);

}

From source file:edu.harvard.mcz.imagecapture.PositionTemplateEditor.java

/**
 * This method initializes jMenuItem1   
 *    /*  w ww  . ja va  2  s.co m*/
 * @return javax.swing.JMenuItem   
 */
private JMenuItem getJMenuItemLoadImage() {
    if (jMenuItem1 == null) {
        jMenuItem1 = new JMenuItem();
        jMenuItem1.setText("Load Image");
        jMenuItem1.setMnemonic(KeyEvent.VK_L);
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jLabelFeedback.setText("");
                final JFileChooser fileChooser = new JFileChooser();
                if (Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                    fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                            .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                }
                //FileNameExtensionFilter filter = new FileNameExtensionFilter("TIFF Images", "tif", "tiff");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "tif", "tiff",
                        "jpg", "jpeg", "png");
                fileChooser.setFileFilter(filter);
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    jLabelFeedback.setText("Loading...");
                    try {
                        setImageFile(fileChooser.getSelectedFile());
                        jLabelFeedback.setText("");
                        drawLayers();
                    } catch (IOException e1) {
                        log.debug(e1);
                        jLabelFeedback.setText("Unable to load image.");
                    }
                }
                drawLayers();
            }
        });
    }
    return jMenuItem1;
}

From source file:com.openbravo.pos.imports.JPanelCSVImport.java

private void jbtnDbDriverLibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDbDriverLibActionPerformed
    resetFields();/*from w ww.j  a v  a2 s  . co m*/

    // If CSV.last_file is null then use c:\ otherwise use saved dir
    JFileChooser chooser = new JFileChooser(last_folder == null ? "C:\\" : last_folder);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("csv files", "csv");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File csvFile = chooser.getSelectedFile();
    // check if a file was selected        
    if (csvFile == null) {
        return;
    }

    File current_folder = chooser.getCurrentDirectory();
    // If we have a file lets save the directory for later use if it's different from the old
    if (last_folder == null || !last_folder.equals(current_folder.getAbsolutePath())) {
        AppConfig CSVConfig = new AppConfig(config_file);
        CSVConfig.load();
        CSVConfig.setProperty("CSV.last_folder", current_folder.getAbsolutePath());
        last_folder = current_folder.getAbsolutePath();

        try {
            CSVConfig.save();
        } catch (IOException ex) {
            Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    String csv = csvFile.getName();
    if (!(csv.trim().equals(""))) {
        csvFileName = csvFile.getAbsolutePath();
        jFileName.setText(csvFileName);
    }
}

From source file:edu.harvard.mcz.imagecapture.jobs.JobSingleBarcodeScan.java

@Override
public void start() {
    startDate = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    setPercentComplete(0);/*from  w ww .ja  v  a  2 s.com*/
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Selecting file to check.");
    String rawOCR = ""; // to hold unparsed ocr output from unit tray label
    //Create a file chooser
    final JFileChooser fileChooser = new JFileChooser();
    if (Singleton.getSingletonInstance().getProperties().getProperties()
            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
        fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
    }
    //FileNameExtensionFilter filter = new FileNameExtensionFilter("TIFF Images", "tif", "tiff");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "tif", "tiff", "jpg", "jpeg",
            "png");
    fileChooser.setFileFilter(filter);
    int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
    setPercentComplete(10);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Scanning file for barcode.");
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File fileToCheck = fileChooser.getSelectedFile();
        Singleton.getSingletonInstance().getProperties().getProperties()
                .setProperty(ImageCaptureProperties.KEY_LASTPATH, fileToCheck.getPath());
        String filename = fileToCheck.getName();
        log.debug("Selected file " + filename + " to scan for barcodes");
        CandidateImageFile.debugCheckHeightWidth(fileToCheck);

        // scan selected file
        PositionTemplate defaultTemplate = null;
        // Figure out which template to use.
        DefaultPositionTemplateDetector detector = new DefaultPositionTemplateDetector();
        String template = "";
        try {
            template = detector.detectTemplateForImage(fileToCheck);
        } catch (UnreadableFileException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
        setPercentComplete(20);
        try {
            defaultTemplate = new PositionTemplate(template);
            log.debug("Set template to: " + defaultTemplate.getTemplateId());
        } catch (NoSuchTemplateException e1) {
            try {
                defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT);
                log.error("Template not recongised, reset template to: " + defaultTemplate.getTemplateId());
            } catch (Exception e2) {
                // We shouldn't end up here - we just asked for the default template by its constant.
                log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT");
                log.trace(e2);
                ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR);
            }
        }
        // TODO: Store the template id for this image with the other image metadata so
        // that we don't have to check again.

        CandidateImageFile scannableFile;
        try {
            scannableFile = new CandidateImageFile(fileToCheck, defaultTemplate);

            String barcode = scannableFile.getBarcodeTextAtFoundTemplate();
            if (scannableFile.getCatalogNumberBarcodeStatus() != CandidateImageFile.RESULT_BARCODE_SCANNED) {
                log.error("Error scanning for barcode: " + barcode);
                barcode = "";
            }
            String exifComment = scannableFile.getExifUserCommentText();
            if (barcode.equals("")
                    && Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment)) {
                // There should be a template for this image, and it shouldn't be the TEMPLATE_NO_COMPONENT_PARTS 
                if (defaultTemplate.getTemplateId().equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) {
                    try {
                        // This will give us a shot at OCR of the text and display of the image parts.
                        defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT);
                        log.error("Barcode not recongised, but exif contains barcode, reset template to: "
                                + defaultTemplate.getTemplateId());
                    } catch (Exception e2) {
                        // We shouldn't end up here - we just asked for the default template by its constant.
                        log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT");
                        log.trace(e2);
                        ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR);
                    }
                }
            }

            log.debug("With template:" + defaultTemplate.getTemplateId());
            log.debug("Barcode=" + barcode);

            setPercentComplete(30);

            String warning = "";
            if (Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) {
                if (!barcode.equals(exifComment)) {
                    warning = "Warning: non-matching QR code barcode and exif Comment";
                    System.out.println(warning);
                }
            }

            Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Loading image.");

            ImageDisplayFrame resultFrame = new ImageDisplayFrame();

            if (Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) {
                resultFrame.setBarcode("QR=" + barcode + " Comment=" + exifComment + " " + warning);
            } else {
                resultFrame.setBarcode("QR=" + barcode);
            }

            try {
                resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null);
            } catch (ImageLoadException e2) {
                System.out.println("Error loading image file.");
                System.out.println(e2.getMessage());
            } catch (BadTemplateException e2) {
                System.out.println("Template doesn't match image file.");
                System.out.println(e2.getMessage());
                try {
                    try {
                        try {
                            template = detector.detectTemplateForImage(fileToCheck);
                        } catch (UnreadableFileException e3) {
                            // TODO Auto-generated catch block
                            e3.printStackTrace();
                        }
                        defaultTemplate = new PositionTemplate(template);
                    } catch (NoSuchTemplateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null);
                } catch (ImageLoadException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BadTemplateException e) {
                    System.out.println("Template doesn't match image file.");
                    System.out.println(e2.getMessage());
                }
            }

            UnitTrayLabel labelRead = null;
            try {
                // Read unitTrayLabelBarcode, failover to OCR and parse UnitTray Label
                rawOCR = "";
                labelRead = scannableFile.getTaxonLabelQRText(defaultTemplate);
                if (labelRead == null) {
                    try {
                        labelRead = scannableFile.getTaxonLabelQRText(new PositionTemplate("Test template 2"));
                    } catch (NoSuchTemplateException e1) {
                        try {
                            labelRead = scannableFile
                                    .getTaxonLabelQRText(new PositionTemplate("Small template 2"));
                        } catch (NoSuchTemplateException e2) {
                            log.error("None of " + defaultTemplate.getName()
                                    + " Test template 2 or Small template 2 were found");
                        }
                    }
                } else {
                    log.debug("Translated UnitTrayBarcode to: " + labelRead.toJSONString());
                }
                if (labelRead != null) {
                    rawOCR = labelRead.toJSONString();
                } else {
                    log.debug("Failing over to OCR with tesseract");
                    rawOCR = scannableFile.getLabelOCRText(defaultTemplate);
                }
                log.debug(rawOCR);
                resultFrame.setRawOCRLabel(rawOCR);
                setPercentComplete(40);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

            setPercentComplete(50);

            resultFrame.pack();
            resultFrame.setVisible(true);
            resultFrame.centerSpecimen();
            resultFrame.center();
            setPercentComplete(60);

            if (persist) {
                // Check that fileToCheck is within imagebase.
                if (!ImageCaptureProperties.isInPathBelowBase(fileToCheck)) {
                    String base = Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                    log.error("Tried to scan file (" + fileToCheck.getPath()
                            + ") outside of base image directory (" + base + ")");
                    throw new UnreadableFileException(
                            "Can't scan and database files outside of base image directory (" + base + ")");
                }

                String state = WorkFlowStatus.STAGE_0;
                Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Connecting to database.");
                // try to parse the raw OCR               
                TaxonNameReturner parser = null;
                if (labelRead != null) {
                    rawOCR = labelRead.toJSONString();
                    state = WorkFlowStatus.STAGE_1;
                    parser = (TaxonNameReturner) labelRead;
                } else {
                    log.debug("Failing over to OCR with tesseract");
                    rawOCR = scannableFile.getLabelOCRText(defaultTemplate);
                    state = WorkFlowStatus.STAGE_0;
                    parser = new UnitTrayLabelParser(rawOCR);
                }

                // Case 1: This is an image of papers associated with a container (a unit tray or a box).
                // This case can be identified by there being no barcode data associated with the image.
                // Action: 
                // A) Check the exifComment to see what metadata is there, if blank, bring up a dialog.
                // Options: A drawer, for which number is captured.  A unit tray, capture ?????????.  A specimen
                // where barcode wasn't read, allow capture of barcode and treat as Case 2.
                // B) Create an image record and store the image metadata (with a null specimen_id).  

                boolean isSpecimenImage = false;
                boolean isDrawerImage = false;
                // Test: is exifComment a barcode:
                if (Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment)
                        || Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) {
                    isSpecimenImage = true;
                    System.out.println("Specimen Image");
                } else {
                    if (exifComment.matches(Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_REGEX_DRAWERNUMBER))) {
                        isDrawerImage = true;
                        System.out.println("Drawer Image");
                    } else {
                        // Ask.
                        System.out.println("Need to ask.");
                        WhatsThisImageDialog askDialog = new WhatsThisImageDialog(resultFrame, fileToCheck);
                        askDialog.setVisible(true);
                        if (askDialog.isSpecimen()) {
                            isSpecimenImage = true;
                            exifComment = askDialog.getBarcode();
                        }
                        if (askDialog.isDrawerImage()) {
                            isDrawerImage = true;
                            exifComment = askDialog.getDrawerNumber();
                        }
                    }
                }

                // applies to both cases.
                ICImageLifeCycle imageCont = new ICImageLifeCycle();
                ICImage tryMe = new ICImage();
                tryMe.setFilename(filename);
                //String path = fileToCheck.getParentFile().getPath();
                String path = ImageCaptureProperties.getPathBelowBase(fileToCheck);
                //String[] bits = rawOCR.split(":");
                List<ICImage> matches = imageCont.findByExample(tryMe);

                // Case 2: This is an image of a specimen and associated labels or an image assocated with 
                // a specimen with the specimen's barcode label in the image.
                // This case can be identified by there being a barcode in a templated position or there 
                // being a barcode in the exif comment tag.  
                // Action: 
                // A) Check if a specimen record exists, if not, create one from the barcode and OCR data.
                // B) Create an image record and store the image metadata.

                // Handle a potential failure case, existing image record without a linked specimen, but which 
                // should have one.
                if (matches.size() == 1 && isSpecimenImage) {
                    ICImage existing = imageCont.findById(matches.get(0).getImageId());
                    if (existing.getSpecimen() == null) {
                        // If the existing image record has no attached specimen, delete it. 
                        // We will create it again from tryMe.
                        try {
                            Singleton.getSingletonInstance().getMainFrame()
                                    .setStatusMessage("Removing existing unlinked image record.");
                            imageCont.delete(existing);
                            matches.remove(0);
                        } catch (SaveFailedException e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }

                if (matches.size() == 0) {
                    String rawBarcode = barcode;
                    if (isSpecimenImage) {
                        Singleton.getSingletonInstance().getMainFrame()
                                .setStatusMessage("Creating new specimen record.");
                        Specimen s = new Specimen();
                        if ((!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode))
                                && Singleton.getSingletonInstance().getBarcodeMatcher()
                                        .matchesPattern(exifComment)) {
                            s.setBarcode(exifComment);
                            barcode = exifComment;
                        } else {
                            if (!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) {
                                // Won't be able to save the specimen record if we end up here.
                                log.error(
                                        "Neither exifComment nor QR Code barcode match the expected pattern for a barcode, but isSpecimenImage got set to true.");
                            }
                            s.setBarcode(barcode);
                        }
                        s.setWorkFlowStatus(state);
                        if (!state.equals(WorkFlowStatus.STAGE_0)) {
                            s.setFamily(parser.getFamily());
                            s.setSubfamily(parser.getSubfamily());
                            s.setTribe(parser.getTribe());
                        } else {
                            s.setFamily("");
                            // Look up likely matches for the OCR of the higher taxa in the HigherTaxon authority file.
                            HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle();
                            if (parser.getTribe().trim().equals("")) {
                                if (hls.isMatched(parser.getFamily(), parser.getSubfamily())) {
                                    // If there is a match, use it.
                                    String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily());
                                    s.setFamily(higher[0]);
                                    s.setSubfamily(higher[1]);
                                } else {
                                    // otherwise use the raw OCR output.
                                    s.setFamily(parser.getFamily());
                                    s.setSubfamily(parser.getSubfamily());
                                }
                                s.setTribe("");
                            } else {
                                if (hls.isMatched(parser.getFamily(), parser.getSubfamily(),
                                        parser.getTribe())) {
                                    String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily(),
                                            parser.getTribe());
                                    s.setFamily(higher[0]);
                                    s.setSubfamily(higher[1]);
                                    s.setTribe(higher[2]);
                                } else {
                                    s.setFamily(parser.getFamily());
                                    s.setSubfamily(parser.getSubfamily());
                                    s.setTribe(parser.getTribe());
                                }
                            }
                            if (!parser.getFamily().equals("")) {
                                // check family against database (with a soundex match)
                                String match = hls.findMatch(parser.getFamily());
                                if (match != null && !match.trim().equals("")) {
                                    s.setFamily(match);
                                }
                            }
                        }
                        // trim family to fit (in case multiple parts of taxon name weren't parsed
                        // and got concatenated into family field.
                        if (s.getFamily().length() > 40) {
                            s.setFamily(s.getFamily().substring(0, 40));
                        }

                        s.setGenus(parser.getGenus());
                        s.setSpecificEpithet(parser.getSpecificEpithet());
                        s.setSubspecificEpithet(parser.getSubspecificEpithet());
                        s.setInfraspecificEpithet(parser.getInfraspecificEpithet());
                        s.setInfraspecificRank(parser.getInfraspecificRank());
                        s.setAuthorship(parser.getAuthorship());
                        s.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                        s.setCollection(((CollectionReturner) parser).getCollection());
                        s.setCreatingPath(ImageCaptureProperties.getPathBelowBase(fileToCheck));
                        s.setCreatingFilename(fileToCheck.getName());
                        if (parser.getIdentifiedBy() != null && parser.getIdentifiedBy().length() > 0) {
                            s.setIdentifiedBy(parser.getIdentifiedBy());
                        }
                        log.debug(s.getCollection());

                        // TODO: non-general workflows

                        // ********* Special Cases **********
                        if (s.getWorkFlowStatus().equals(WorkFlowStatus.STAGE_0)) {
                            // ***** Special case, images in ent-formicidae 
                            //       get family set to Formicidae if in state OCR.
                            if (path.contains("formicidae")) {
                                s.setFamily("Formicidae");
                            }
                        }
                        s.setLocationInCollection(LocationInCollection.getDefaultLocation());
                        if (s.getFamily().equals("Formicidae")) {
                            // ***** Special case, families in Formicidae are in Ant collection
                            s.setLocationInCollection(LocationInCollection.GENERALANT);
                        }
                        // ********* End Special Cases **********

                        s.setCreatedBy(ImageCaptureApp.APP_NAME + " " + ImageCaptureApp.APP_VERSION);
                        SpecimenLifeCycle sh = new SpecimenLifeCycle();
                        try {
                            sh.persist(s);
                            s.attachNewPart();
                        } catch (SpecimenExistsException e) {
                            log.debug(e);
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    filename + " " + barcode + " \n" + e.getMessage(),
                                    "Specimen Exists, linking Image to existing record.",
                                    JOptionPane.ERROR_MESSAGE);
                            List<Specimen> checkResult = sh.findByBarcode(barcode);
                            if (checkResult.size() == 1) {
                                s = checkResult.get(0);
                            }
                        } catch (SaveFailedException e) {
                            // Couldn't save, but for some reason other than the
                            // specimen record already existing.
                            log.debug(e);
                            try {
                                List<Specimen> checkResult = sh.findByBarcode(barcode);
                                if (checkResult.size() == 1) {
                                    s = checkResult.get(0);
                                }
                                // Drawer number with length limit (and specimen that fails to save at over this length makes
                                // a good canary for labels that parse very badly.
                                String badParse = "";
                                if (((DrawerNameReturner) parser).getDrawerNumber().length() > MetadataRetriever
                                        .getFieldLength(Specimen.class, "DrawerNumber")) {
                                    badParse = "Parsing problem. \nDrawer number is too long: "
                                            + s.getDrawerNumber() + "\n";
                                }
                                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                        filename + " " + barcode + " \n" + badParse + e.getMessage(),
                                        "Badly parsed OCR", JOptionPane.ERROR_MESSAGE);
                            } catch (Exception err) {
                                log.error(e);
                                log.error(err);
                                // TODO: Add a general error handling/inform user class.
                                // Cause of exception is not likely to be drawer number now that drawer number
                                // length is enforced in Specimen.setDrawerNumber, but the text returned by the parser
                                // might indicate very poor OCR as a cause.
                                String badParse = ((DrawerNameReturner) parser).getDrawerNumber();
                                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                        filename + " " + barcode + "\n" + badParse + e.getMessage(),
                                        "Save Failed", JOptionPane.ERROR_MESSAGE);
                                s = null;
                            }
                        }
                        setPercentComplete(70);
                        if (s != null) {
                            tryMe.setSpecimen(s);
                        }
                    }
                    tryMe.setRawBarcode(rawBarcode);
                    if (isDrawerImage) {
                        tryMe.setDrawerNumber(exifComment);
                    } else {
                        tryMe.setRawExifBarcode(exifComment);
                        tryMe.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                    }
                    tryMe.setRawOcr(rawOCR);
                    tryMe.setTemplateId(defaultTemplate.getTemplateId());
                    tryMe.setPath(path);
                    if (tryMe.getMd5sum() == null || tryMe.getMd5sum().length() == 0) {
                        try {
                            tryMe.setMd5sum(DigestUtils.md5Hex(new FileInputStream(fileToCheck)));
                        } catch (FileNotFoundException e) {
                            log.error(e.getMessage());
                        } catch (IOException e) {
                            log.error(e.getMessage());
                        }
                    }
                    try {
                        imageCont.persist(tryMe);
                    } catch (SaveFailedException e) {
                        // TODO Auto-generated catch block
                        log.error(e.getMessage());
                        e.printStackTrace();
                    }

                    setPercentComplete(80);
                    if (isSpecimenImage) {
                        SpecimenControler controler = null;
                        try {
                            controler = new SpecimenControler(tryMe.getSpecimen());
                            controler.setTargetFrame(resultFrame);
                        } catch (NoSuchRecordException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(tryMe.getSpecimen(),
                                controler);
                        resultFrame.addWest((JPanel) sPane);
                        if (!tryMe.getRawBarcode().equals(tryMe.getRawExifBarcode())) {
                            if (Singleton.getSingletonInstance().getProperties().getProperties()
                                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE)
                                    .equals("true")) {
                                // If so configured, warn about missmatch 
                                sPane.setWarning(
                                        "Warning: Scanned Image has missmatch between barcode and comment.");
                            }
                        }
                    }
                    resultFrame.center();
                } else {
                    // found one or more matching image records.
                    setPercentComplete(80);
                    Singleton.getSingletonInstance().getMainFrame()
                            .setStatusMessage("Loading existing image record.");
                    ICImage existing = imageCont.findById(matches.get(0).getImageId());
                    System.out.println(existing.getRawBarcode());
                    existing.setRawBarcode(barcode);
                    if (isDrawerImage) {
                        existing.setDrawerNumber(exifComment);
                    } else {
                        existing.setRawExifBarcode(exifComment);
                    }
                    existing.setTemplateId(defaultTemplate.getTemplateId());
                    if (existing.getPath() == null || existing.getPath().equals("")) {
                        existing.setPath(path);
                    }
                    if (existing.getDrawerNumber() == null || existing.getDrawerNumber().equals("")) {
                        existing.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                    }
                    try {
                        imageCont.attachDirty(existing);
                    } catch (SaveFailedException e) {
                        // TODO Auto-generated catch block
                        log.error(e.getMessage());
                        e.printStackTrace();
                    }
                    if (isSpecimenImage) {
                        SpecimenControler controler = null;
                        try {
                            controler = new SpecimenControler(existing.getSpecimen());
                            controler.setTargetFrame(resultFrame);
                            System.out.println(existing.getSpecimen().getBarcode());
                        } catch (NullPointerException e1) {
                            log.debug("Specimen barcode not set");
                        } catch (NoSuchRecordException e) {
                            // Failure case 
                            log.error(e.getMessage(), e);
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    filename + " " + barcode + "\n"
                                            + "Existing Image record with no Specimen Record. "
                                            + e.getMessage(),
                                    "Save Failed.", JOptionPane.ERROR_MESSAGE);
                        }
                        SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(existing.getSpecimen(),
                                controler);
                        resultFrame.addWest((JPanel) sPane);
                        resultFrame.center();
                        resultFrame.setActiveTab(ImageDisplayFrame.TAB_LABELS);
                        resultFrame.fitPinLabels();
                        if (!existing.getRawBarcode().equals(existing.getRawExifBarcode())) {
                            if (Singleton.getSingletonInstance().getProperties().getProperties()
                                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE)
                                    .equals("true")) {
                                sPane.setWarning(
                                        "Warning: Scanned Image has missmatch between barcode and comment.");
                            }
                        }
                    }
                    setPercentComplete(90);
                }
            }
        } catch (UnreadableFileException e1) {
            log.error("Unable to read selected file." + e1.getMessage());
        } catch (OCRReadException e) {
            log.error("Failed to OCR file." + e.getMessage());
        }
    } else {
        System.out.println("No file selected from dialog.");
    }
    setPercentComplete(100);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("");
    SpecimenLifeCycle sls = new SpecimenLifeCycle();
    Singleton.getSingletonInstance().getMainFrame().setCount(sls.findSpecimenCount());
    Singleton.getSingletonInstance().getJobList().removeJob((RunnableJob) this);
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private JFileChooser getWavFileChooser() {
    JFileChooser wavChooser = new JFileChooser(new File(System.getProperty("user.dir") + "/wav"));
    wavChooser.setDialogTitle("WAV File Chooser, select or enter WAV file for recording");

    wavChooser.setFileFilter(new FileFilter() {
        @Override/*from   w  ww .ja v  a2  s.  co m*/
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().indexOf(".wav") > 0;
        }

        @Override
        public String getDescription() {
            return "WAV files";
        }
    });

    return wavChooser;
}

From source file:mondrian.gui.Workbench.java

private void openMenuItemActionPerformed(ActionEvent evt) {
    JFileChooser jfc = new JFileChooser();
    try {/*from w  w w .  java  2 s .c  o m*/
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().toLowerCase().endsWith(".xml") || pathname.isDirectory();
            }

            public String getDescription() {
                return getResourceConverter().getString("workbench.open.schema.file.type",
                        "Mondrian Schema files (*.xml)");
            }
        });

        String lastUsed = getWorkbenchProperty(LAST_USED1_URL);

        if (lastUsed != null) {
            jfc.setCurrentDirectory(new File(new URI(lastUsed)));
        }
    } catch (Exception ex) {
        LOGGER.error("Could not set file chooser", ex);
    }
    MondrianProperties.instance();
    if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
            setLastUsed(jfc.getSelectedFile().getName(), jfc.getSelectedFile().toURI().toURL().toString());
        } catch (MalformedURLException e) {
            LOGGER.error(e);
        }

        openSchemaFrame(jfc.getSelectedFile(), false);
    }
}

From source file:org.jets3t.apps.uploader.Uploader.java

/**
 * Handles GUI actions./*from w  w  w  .ja  v  a2  s.c  om*/
 */
public void actionPerformed(ActionEvent actionEvent) {
    if ("Next".equals(actionEvent.getActionCommand())) {
        wizardStepForward();
    } else if ("Back".equals(actionEvent.getActionCommand())) {
        wizardStepBackward();
    } else if ("ChooseFile".equals(actionEvent.getActionCommand())) {
        JFileChooser fileChooser = new JFileChooser();

        if (validFileExtensions.size() > 0) {
            UploaderFileExtensionFilter filter = new UploaderFileExtensionFilter("Allowed files",
                    validFileExtensions);
            fileChooser.setFileFilter(filter);
        }

        fileChooser.setMultiSelectionEnabled(fileMaxCount > 1);
        fileChooser.setDialogTitle("Choose file" + (fileMaxCount > 1 ? "s" : "") + " to upload");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Choose file" + (fileMaxCount > 1 ? "s" : ""));

        int returnVal = fileChooser.showOpenDialog(ownerFrame);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        List fileList = new ArrayList();
        if (fileChooser.getSelectedFiles().length > 0) {
            fileList.addAll(Arrays.asList(fileChooser.getSelectedFiles()));
        } else {
            fileList.add(fileChooser.getSelectedFile());
        }
        if (checkProposedUploadFiles(fileList)) {
            wizardStepForward();
        }
    } else if ("CancelUpload".equals(actionEvent.getActionCommand())) {
        if (uploadCancelEventTrigger != null) {
            uploadCancelEventTrigger.cancelTask(this);
            progressBar.setValue(0);
        } else {
            log.warn("Ignoring attempt to cancel file upload when cancel trigger is not available");
        }
    } else {
        log.warn("Unrecognised action command, ignoring: " + actionEvent.getActionCommand());
    }
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void fireSaveScreenshotEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireSaveScreenshotEvent
    String dir = GlobalOptions.getProperty("screen.dir");

    JFileChooser chooser = null;
    try {//from ww  w  . j ava 2 s .  com
        chooser = new JFileChooser(dir);
    } catch (Exception e) {
        JOptionPaneHelper.showErrorBox(this,
                "Konnte Dateiauswahldialog nicht ffnen.\nMglicherweise verwendest du Windows Vista. Ist dies der Fall, beende DS Workbench, klicke mit der rechten Maustaste auf DSWorkbench.exe,\n"
                        + "whle 'Eigenschaften' und deaktiviere dort unter 'Kompatibilitt' den Windows XP Kompatibilittsmodus.",
                "Fehler");
        return;
    }
    chooser.setDialogTitle("Speichern unter...");
    chooser.setSelectedFile(new File("map"));

    final String type = (String) jFileTypeChooser.getSelectedItem();
    chooser.setFileFilter(new FileFilter() {

        @Override
        public boolean accept(File f) {
            return (f != null) && (f.isDirectory() || f.getName().endsWith(type));
        }

        @Override
        public String getDescription() {
            return "*." + type;
        }
    });

    int ret = chooser.showSaveDialog(jScreenshotControl);

    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            File f = chooser.getSelectedFile();
            String file = f.getCanonicalPath();
            if (!file.endsWith(type)) {
                file += "." + type;
            }
            File target = new File(file);
            if (target.exists()) {
                //ask if overwrite
                if (JOptionPaneHelper.showQuestionConfirmBox(jScreenshotControl,
                        "Existierende Datei berschreiben?", "berschreiben", "Nein",
                        "Ja") != JOptionPane.YES_OPTION) {
                    return;
                }
            }
            ImageIO.write(mScreenshotPanel.getResult(jTransparancySlider.getValue()), type, target);
            GlobalOptions.addProperty("screen.dir", target.getParent());

        } catch (Exception e) {
            logger.error("Failed to write map shot", e);
        }
    }
}

From source file:com.freedomotic.jfrontend.MainWindow.java

/**
 *
 * @param evt/*from w ww  .  ja  v a  2  s  .c  o  m*/
 */
private void mnuRoomBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRoomBackgroundActionPerformed

    ZoneLogic zone = drawer.getSelectedZone();

    if (zone == null) {
        JOptionPane.showMessageDialog(this, i18n.msg("select_room_first"));
    } else {
        final JFileChooser fc = new JFileChooser(Info.PATHS.PATH_RESOURCES_FOLDER);
        OpenDialogFileFilter filter = new OpenDialogFileFilter();
        filter.addExtension("png");
        filter.addExtension("jpeg");
        filter.addExtension("jpg");
        filter.setDescription("Image files (png, jpeg)");
        fc.addChoosableFileFilter(filter);
        fc.setFileFilter(filter);

        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            LOG.info("Opening room background file \"{}\"", file.getAbsolutePath());
            zone.getPojo().setTexture(file.getName());
            drawer.setNeedRepaint(true);
            frameMap.validate();
        }
    }
}