Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:net.liuxuan.device.w3330.JIF_DrawChart_w3330.java

public void openFiletoCurve() throws NumberFormatException {
    String tempstr = jFormattedTextField_temp.getText();
    int tempint = Integer.parseInt(tempstr);
    dropinterval = tempint;/*w w w .java  2 s .c  om*/

    //??
    //??0?1
    double oldzero = -1000;
    long oldzerotime = -1;
    double oldstatus = -1;

    filterds = new double[dropinterval];
    SimpleDateFormat sdfx = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]");
    //        String content;
    List<String> fileContentStringList = null;

    JFileChooser jfc = initFileChooser();

    //?lastpath
    String latestPath = (String) datas.get("lastpath");

    File currentDir = null;
    FileSystemView fsv = FileSystemView.getFileSystemView();
    if (latestPath == null) {
        //?
        currentDir = fsv.getHomeDirectory();
    } else {
        currentDir = new File(latestPath);
        if (currentDir.exists() && currentDir.isDirectory()) {
        } else {
            currentDir = fsv.getHomeDirectory();
        }
    }
    jfc.setCurrentDirectory(currentDir);

    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        //            String filepath = jfc.getSelectedFile().getAbsolutePath();
        //lastpath
        datas.put("lastpath", jfc.getSelectedFile().isDirectory() ? jfc.getSelectedFile().getAbsolutePath()
                : jfc.getSelectedFile().getParent());

        if (jfc.getSelectedFile() == null) {
            //
            System.out.println("!!");
            return;
        }
        try {
            fileContentStringList = Files.readLines(jfc.getSelectedFile(), Charsets.ISO_8859_1);

        } catch (IOException ex) {
            Logger.getLogger(JIF_DrawChart_w3330.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        System.out.println("!!");
        return;
    }

    //??,dropinterval
    parseFileToDataStructure(fileContentStringList, dropinterval);
    if (metadatas.size() == 0) {
        System.out.println("?");
        return;
    } else {
        chartPanel.getChart().setTitle("" + jfc.getSelectedFile().getName());
        System.out.println("" + jfc.getSelectedFile().getName());
        System.out.println(String.format("?%d", fileContentStringList.size()));
        System.out.println(String.format("?%d", metadatas.size()));
    }

    //?
    KalmanFilterHolder kfh_AmbiTemp = new KalmanFilterHolder(25d);//?
    KalmanFilterHolder kfh_ppm = new KalmanFilterHolder(13d);//?

    //===============kalman?
    clearChart();//?

    tsNotifyFalse();//?

    //??
    for (int i = 0; i < metadatas.size(); i++) {
        W3330MetaData data = metadatas.get(i);

        if (oldzero < -1) {
            oldzero = data.zero;
            oldzerotime = data.time.getTime();
        } else if (oldzero != data.zero) {
            oldzero = data.zero;
            oldzerotime = data.time.getTime();
            //
            Color purple = new Color(139, 0, 255);
            String Labelstr = String.format("%.4f", data.zero);
            chartDrawHerizonLine(data, purple, Labelstr);
        }

        //status 1?? 2 ? 3 4 5?? 6 7?? 8 9? 0 
        if (oldstatus != data.status) {
            oldstatus = data.status;
            //
            Color purple = new Color(139, 0, 255);
            String Labelstr;

            switch ((int) data.status) {
            case 1:
                Labelstr = "??";
                break;
            case 2:
                Labelstr = "?";
                break;
            case 3:
                Labelstr = "";
                break;
            case 4:
                Labelstr = "";
                break;
            case 5:
                Labelstr = "??";
                break;
            case 6:
                Labelstr = "";
                break;
            case 7:
                Labelstr = "??";
                break;
            case 8:
                Labelstr = "";
                break;
            case 9:
                Labelstr = "?";
                break;
            case 0:
                Labelstr = "";
                break;
            default:
                Labelstr = "???status=" + data.status;
                //                        throw new AssertionError();
            }
            //                Labelstr = String.format("%.4f", data.zero);
            chartDrawVerticalLine(data, purple, Labelstr);

            //?ppm
            kfh_ppm = new KalmanFilterHolder(data.wppm);//?
        }

        //
        data.filter1 = kfh_AmbiTemp.getEstimation(data.temp3);
        data.filter2 = kfh_ppm.getEstimation(data.wppm);

        //fitting2 = kalmanfilter2.getStateEstimation()[0]-(fitting-25)*0.78;
        //                        fitting2 = wppm-(fitting-25)*0.7;//ppm
        //                        fitting = kalmanfilter.getStateEstimation()[0];
        // state estimate shouldn't be larger than the measurement noise
        //                        double diff = Math.abs(x.getEntry(0) - kalmanfilter.getStateEstimation()[0]);
        /*
                     //?
                     if (filterpoint < filterds.length) {
                     //?
                     filterds[filterpoint] = temp3;
                     filterpoint++;
                     fitting = wppm;
                     } else {
                
                     //???
                     filterds[filterpoint % filterds.length] = temp3;
                     double[] copy = Arrays.copyOf(filterds, filterds.length);
                     Arrays.sort(copy);
                
                     double total = 0;
                     for (int idx = copy.length / 4; idx < copy.length - copy.length / 4; idx++) {
                     total += copy[idx];
                     }
                     temp3 = total / (copy.length - copy.length / 4 - copy.length / 4);
                     filterpoint++;
                     //0.78?
                     //????
                     //                            fitting = wppm-(filterds[filterpoint%filterds.length]-25)*0.78;
                     fitting = wppm - (temp3 - 25) * 0.78;
                     }
                     */
        ts_wppm.addOrUpdate(new Millisecond(data.time), data.wppm);
        ts_wppm_zero.addOrUpdate(new Millisecond(data.time), data.ppmzero);
        ts_wvtr.addOrUpdate(new Millisecond(data.time), data.wvtr);
        //??100??100
        ts_flux.addOrUpdate(new Millisecond(data.time), data.flux);
        //25????25
        ts_tempambi.addOrUpdate(new Millisecond(data.time), data.temp3);
        //38????38
        ts_tempcell.addOrUpdate(new Millisecond(data.time), data.temp1);
        //?
        //status 1?? 2 ? 3 4 5?? 6 7?? 8 9? 0 
        ts_status.addOrUpdate(new Millisecond(data.time), data.status);
        ts_fitting.addOrUpdate(new Millisecond(data.time), data.filter1);
        data.fitting2 = data.wppm - (data.temp3 - 25) * 1.25;//??
        //data.fitting2 = data.wppm *(273.15+25)/(273.15+data.temp3);//??
        //            data.fitting2= data.wppm+(data.flux-40)*12.4;
        //            ts_fitting2.addOrUpdate(new Millisecond(data.time), data.fitting2);
        ts_fitting2.addOrUpdate(new Millisecond(data.time), data.filter2);
        //fitting2 ?
        /*
         int step = 20;
         step = tempint;
         if (data.zero > 0 && i % step == 0 && i > 2 * step) {
         //??
         double value_wvtr = (data.wppm - data.zero) * 0.02161956;
         double total = 0;
         double value_avg = 0;
         double old1 = (metadatas.get(i - step).wppm - data.zero);
         double old2 = (metadatas.get(i - step * 2).wppm - data.zero);
         total = (old1 + old2 + (data.wppm - data.zero)) * 0.02161956;
         value_avg = total / 3;
         double diff = (value_wvtr - value_avg) / value_avg;
         System.out.println(String.format(":%s?%.4f?%.4f???%.4f%%", sdfx.format(data.time), value_wvtr, value_avg, diff * 100));
         ts_fitting2.addOrUpdate(new Millisecond(data.time), data.wppm - old1 - data.zero);
         }
         */
    }

    tsNotifyTrue();//
}

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

/**
 * This method initializes jMenuItem1   
 *    //from ww w . j  av a 2s  .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:fur.shadowdrake.minecraft.InstallPanel.java

private void browseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseActionPerformed
    JFileChooser fc = new JFileChooser(new File(dirBox.getText()));

    fc.setFileHidingEnabled(false);/*w  w w  . j  av  a 2  s .  c o m*/
    fc.setDialogTitle("Select directory");
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        dirBox.setText(fc.getSelectedFile().toString());
    }
}

From source file:grupob.TipoProceso.java

private void seleccionarHuellasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seleccionarHuellasActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setDialogTitle("Seleccionar Carpeta");
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        if (!Utils.validarRutaImagenHuella(selectedFile.getAbsolutePath(), 1)) {
            JOptionPane.showMessageDialog(null,
                    "Debe seleccionar una carpeta con archivos JPG con la cantidad de registros de votantes exacta.");
        } else {//w  w w .ja v a 2s . c  o  m
            textConfHuellas.setText("" + selectedFile);
        }
        //            Recorte.rutaHuella=""+selectedFile;
    }
}

From source file:grupob.TipoProceso.java

private void seleccionarFirmasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seleccionarFirmasActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setDialogTitle("Seleccionar Carpeta");
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        if (!Utils.validarRutaImagenHuella(selectedFile.getAbsolutePath(), 1)) {
            JOptionPane.showMessageDialog(null,
                    "Debe seleccionar una carpeta con archivos JPG con la cantidad de registros de votantes exacta.");
        } else {/* www  . j a va 2 s .  c om*/
            textConfFirmas.setText("" + selectedFile);
        }
        //            Recorte.rutaFirma=""+selectedFile;            
    }
}

From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java

/**
 * New language 'project'// w w w  .  j a v a2s .c  om
 */
protected void doNewLocale() {
    if (!checkForChanges()) {
        return;
    }

    ChooseFromListDlg<LanguageEntry> ldlg = new ChooseFromListDlg<LanguageEntry>((Frame) getTopWindow(),
            getResourceString("StrLocalizerApp.ChooseLanguageDlgTitle"), languages);
    UIHelper.centerAndShow(ldlg);
    if (ldlg.isCancelled() || ldlg.getSelectedObject() == null) {
        return;
    }

    JFileChooser fdlg = new JFileChooser();
    fdlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int fdlgResult = fdlg.showOpenDialog(null);
    if (fdlgResult != JFileChooser.APPROVE_OPTION) {
        return;
    }

    File destDir = fdlg.getSelectedFile();

    destLanguage = ldlg.getSelectedObject();
    final String newLang = destLanguage.getEnglishName();
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            destLbl.setText(newLang + ":");
        }
    });

    setupSrcFiles(getDefaultPath());
    setupDestFiles(ldlg.getSelectedObject().getCode(), destDir.getPath());

    for (StrLocaleFile file : destFiles) {
        file.save();
    }
    currentPath = destDir.getPath();
    newSrcFile(getResourcesFile());
}

From source file:DesktopAppTest.java

public DesktopAppFrame() {
    setLayout(new GridBagLayout());
    final JFileChooser chooser = new JFileChooser();
    JButton fileChooserButton = new JButton("...");
    final JTextField fileField = new JTextField(20);
    fileField.setEditable(false);/*from   ww w . j  ava 2s  .  c om*/
    JButton openButton = new JButton("Open");
    JButton editButton = new JButton("Edit");
    JButton printButton = new JButton("Print");
    final JTextField browseField = new JTextField();
    JButton browseButton = new JButton("Browse");
    final JTextField toField = new JTextField();
    final JTextField subjectField = new JTextField();
    JButton mailButton = new JButton("Mail");

    openButton.setEnabled(false);
    editButton.setEnabled(false);
    printButton.setEnabled(false);
    browseButton.setEnabled(false);
    mailButton.setEnabled(false);

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN))
            openButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.EDIT))
            editButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.PRINT))
            printButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.BROWSE))
            browseButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.MAIL))
            mailButton.setEnabled(true);
    }

    fileChooserButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chooser.showOpenDialog(DesktopAppFrame.this) == JFileChooser.APPROVE_OPTION)
                fileField.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    });

    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().open(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    editButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().edit(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    printButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().print(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    browseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI(browseField.getText()));
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    mailButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String subject = percentEncode(subjectField.getText());
                URI uri = new URI("mailto:" + toField.getText() + "?subject=" + subject);

                System.out.println(uri);
                Desktop.getDesktop().mail(uri);
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    JPanel buttonPanel = new JPanel();
    ((FlowLayout) buttonPanel.getLayout()).setHgap(2);
    buttonPanel.add(openButton);
    buttonPanel.add(editButton);
    buttonPanel.add(printButton);

    add(fileChooserButton, new GBC(0, 0).setAnchor(GBC.EAST).setInsets(2));
    add(fileField, new GBC(1, 0).setFill(GBC.HORIZONTAL));
    add(buttonPanel, new GBC(2, 0).setAnchor(GBC.WEST).setInsets(0));
    add(browseField, new GBC(1, 1).setFill(GBC.HORIZONTAL));
    add(browseButton, new GBC(2, 1).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("To:"), new GBC(0, 2).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(toField, new GBC(1, 2).setFill(GBC.HORIZONTAL));
    add(mailButton, new GBC(2, 2).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("Subject:"), new GBC(0, 3).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(subjectField, new GBC(1, 3).setFill(GBC.HORIZONTAL));

    pack();
}

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  2s  .c o m
    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:com.archivas.clienttools.arcmover.gui.panels.ProfilePanel.java

private String browseDirectory() {
    if (getSelectedProfile() != FileSystemProfile.LOCAL_FILESYSTEM_PROFILE) {
        // browse only supported on LFS
        return null;
    }//from www.ja v  a2s.c  o m

    String loadPath = currentDir.getPath();
    JFileChooser chooser = new JFileChooser(loadPath);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int retVal = chooser.showOpenDialog(this);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile().getAbsolutePath();
    } else {
        return null;
    }
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

private String SelectFile() {
    JFileChooser choose = new JFileChooser();
    int returnVal = choose.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = choose.getSelectedFile();
        return file.getAbsolutePath();
    } else {/*  w  w w.  j  av  a2 s  . com*/
        //System.out.println("File access cancelled by user.");
        return "";
    }
}