Example usage for javax.swing JFileChooser APPROVE_OPTION

List of usage examples for javax.swing JFileChooser APPROVE_OPTION

Introduction

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

Prototype

int APPROVE_OPTION

To view the source code for javax.swing JFileChooser APPROVE_OPTION.

Click Source Link

Document

Return value if approve (yes, ok) is chosen.

Usage

From source file:it.unibas.spicygui.controllo.file.ActionLoadTGDs.java

@Override
public void performAction() {
    this.executeInjection();
    JFileChooser chooser = vista.getFileChooserApriTGD();
    File file;/*  w  w  w  . ja  va 2 s  . c om*/
    int returnVal = chooser.showOpenDialog(WindowManager.getDefault().getMainWindow());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            String fileAbsoluteFile = file.getPath();
            ParseMappingTask generator = new ParseMappingTask();
            //giannisk
            Scenarios.getNextFreeNumber();
            MappingTask mappingTask = generator.generateMappingTask(fileAbsoluteFile);
            gestioneScenario(mappingTask);
            this.actionViewSchema.performAction();
            enableActions();
        } catch (Exception ex) {
            DialogDisplayer.getDefault()
                    .notify(new NotifyDescriptor.Message(
                            NbBundle.getMessage(Costanti.class, Costanti.OPEN_ERROR) + " : " + ex.getMessage(),
                            DialogDescriptor.ERROR_MESSAGE));
            logger.error(ex);
        }
    }
}

From source file:es.emergya.ui.gis.popups.SaveGPXDialog.java

private SaveGPXDialog(final List<Layer> capas) {
    super("Consulta de Posiciones GPS");
    setResizable(false);/*  w  w  w  .j a v  a  2 s. c  o  m*/
    setAlwaysOnTop(true);
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    JPanel dialogo = new JPanel(new BorderLayout());
    dialogo.setBackground(Color.WHITE);
    dialogo.setBorder(new EmptyBorder(10, 10, 10, 10));

    JPanel central = new JPanel(new FlowLayout());
    central.setOpaque(false);
    final JTextField nombre = new JTextField(15);
    nombre.setEditable(false);
    central.add(nombre);
    final JButton button = new JButton("Examinar...", LogicConstants.getIcon("button_nuevo"));
    central.add(button);
    final JButton aceptar = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showSaveDialog(SaveGPXDialog.this) == JFileChooser.APPROVE_OPTION) {
                nombre.setText(fileChooser.getSelectedFile().getAbsolutePath());
                aceptar.setEnabled(true);
            }
        }
    });

    dialogo.add(central, BorderLayout.CENTER);

    JPanel botones = new JPanel(new FlowLayout());
    botones.setOpaque(false);

    aceptar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String base_url = nombre.getText() + "_";
            for (Layer layer : capas) {
                if (layer instanceof GpxLayer) {
                    GpxLayer gpxLayer = (GpxLayer) layer;
                    File f = new File(base_url + gpxLayer.name + ".gpx");

                    boolean sobreescribir = !f.exists();

                    try {
                        while (!sobreescribir) {
                            String original = f.getCanonicalPath();
                            f = checkFileOverwritten(nombre, f);
                            sobreescribir = !f.exists() || original.equals(f.getCanonicalPath());
                        }
                    } catch (NullPointerException t) {
                        log.debug("Cancelando creacion de fichero: " + t);
                        sobreescribir = false;
                    } catch (Throwable t) {
                        log.error("Error comprobando la sobreescritura", t);
                        sobreescribir = false;
                    }

                    if (sobreescribir) {
                        try {
                            f.createNewFile();
                        } catch (IOException e1) {
                            log.error(e1, e1);
                        }
                        if (!(f.isFile() && f.canWrite()))
                            JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                    "No tengo permiso para escribir en " + f.getAbsolutePath());
                        else {
                            try {
                                OutputStream out = new FileOutputStream(f);
                                GpxWriter writer = new GpxWriter(out);
                                writer.write(gpxLayer.data);
                                out.close();
                            } catch (Throwable t) {
                                log.error("Error al escribir el gpx", t);
                                JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                        "Ocurri un error al escribir en " + f.getAbsolutePath());
                            }
                        }
                    } else
                        log.error("Por errores anteriores no se escribio el fichero");
                } else
                    log.error("Una de las capas no era gpx: " + layer.name);
            }
            SaveGPXDialog.this.dispose();

        }

        private File checkFileOverwritten(final JTextField nombre, File f) throws Exception {
            String nueva = JOptionPane.showInputDialog(nombre, i18n.getString("savegpxdialog.overwrite"),
                    "Sobreescribir archivo", JOptionPane.QUESTION_MESSAGE, null, null, f.getCanonicalPath())
                    .toString();
            log.debug("Nueva ruta: " + nueva);
            return new File(nueva);
        }
    });

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            SaveGPXDialog.this.dispose();
        }
    });

    aceptar.setEnabled(false);
    botones.add(aceptar);
    botones.add(cancelar);
    dialogo.add(botones, BorderLayout.SOUTH);

    add(dialogo);
    setPreferredSize(new Dimension(300, 200));
    pack();

    int x;
    int y;

    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }

    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }

        @Override
        public void windowClosing(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }
    });
}

From source file:visualizer.datamining.dataanalysis.CreateLineGraph.java

private void saveImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveImageButtonActionPerformed
    int result = SaveDialog.showSaveDialog(new PNGFilter(), this, "image.png");

    if (result == JFileChooser.APPROVE_OPTION) {
        String filename = SaveDialog.getFilename();

        try {//  www . j  av a 2 s .com
            BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            panel.paint(image.getGraphics());
            ImageIO.write(image, "png", new File(filename));
        } catch (IOException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:my.grafos.Maquina.java

static void abrirGrafo() throws FileNotFoundException, IOException, ClassNotFoundException {
    /*       FileInputStream fis = new FileInputStream("d:\\t.xml");
    ObjectInputStream ois = new ObjectInputStream(fis);
    ArrayList<Aresta> leituraListaistaArestas = (ArrayList<Aresta>) ois.readObject();
    ois.close();/*from   w w  w .  jav a  2 s.com*/
    Fabrica.listaArestas = leituraListaistaArestas;
     */

    a = 0;
    final JFileChooser fc = new JFileChooser();
    //Handle open button action.
    int returnVal = fc.showOpenDialog(null);
    File file = fc.getSelectedFile();
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();
        //This is where a real application would open the file.
        System.out.println("Opening: " + file.getName() + "." + "\n");

    } else {
        System.out.println("Open command cancelled by user." + "\n");
    }
    StringBuilder arestaBuilder = new StringBuilder();
    StringBuilder verticeBuilder = new StringBuilder();
    String line;
    try {
        InputStream inputstream = new BufferedInputStream(new FileInputStream(file.getPath()));
        BufferedReader r = new BufferedReader(new InputStreamReader(inputstream));
        while ((line = r.readLine()) != null && !line.contains("</list>")) {
            arestaBuilder.append(line);
            arestaBuilder.append("\n");
        }
        arestaBuilder.append("</list>");
        verticeBuilder.append("<list>\n");

        while ((line = r.readLine()) != null) {
            verticeBuilder.append(line);
            verticeBuilder.append("\n");
        }
    } catch (IOException e) {
    }
    Fabrica.xmlA = arestaBuilder.toString();
    Fabrica.xmlV = verticeBuilder.toString();
    Fabrica.listaArestas = (ArrayList<Aresta>) xstream.fromXML(xmlA);
    Fabrica.listaVertices = (ArrayList<Vertice>) xstream.fromXML(xmlV);
}

From source file:com.diversityarrays.kdxplore.vistool.VisToolbarFactory.java

static public VisToolToolBar create(final String title, final JComponent comp, final Closure<File> snapshotter,
        final VisToolDataProvider visToolDataProvider, boolean floatable, final String[] imageSuffixes) {
    Window window = GuiUtil.getOwnerWindow(comp);

    boolean anyButtons = false;

    final JCheckBox keepOnTop;

    if (window == null) {
        keepOnTop = null;/*from w w w . j  a v a 2 s.  c o m*/
    } else {
        anyButtons = true;
        keepOnTop = new JCheckBox(Msg.OPTION_KEEP_ON_TOP(), true);

        keepOnTop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                window.setAlwaysOnTop(keepOnTop.isSelected());
            }
        });
        window.setAlwaysOnTop(keepOnTop.isSelected());

        //         buttons.add(keepOnTop);

        final PropertyChangeListener alwaysOnTopListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                keepOnTop.setSelected(window.isAlwaysOnTop());
            }
        };
        window.addPropertyChangeListener(PROPERTY_ALWAYS_ON_TOP, alwaysOnTopListener);

        window.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                window.removeWindowListener(this);
                window.removePropertyChangeListener(PROPERTY_ALWAYS_ON_TOP, alwaysOnTopListener);
            }
        });
    }

    final JButton cameraButton;
    if (snapshotter == null) {
        cameraButton = null;
    } else {
        Action cameraAction = new AbstractAction(Msg.ACTION_SNAPSHOT()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (chooser == null) {
                    chooser = new JFileChooser();
                    chooser.setFileFilter(new FileFilter() {
                        @Override
                        public boolean accept(File f) {
                            if (!f.isFile()) {
                                return true;
                            }
                            String loname = f.getName().toLowerCase();
                            for (String sfx : imageSuffixes) {
                                if (loname.endsWith(sfx)) {
                                    return true;
                                }
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Msg.DESC_IMAGE_FILE();
                        }
                    });
                    chooser.setMultiSelectionEnabled(false);
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                }

                if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(comp)) {
                    File file = chooser.getSelectedFile();
                    snapshotter.execute(file);
                }
            }
        };

        ImageIcon icon = loadIcon("camera-24.png"); //$NON-NLS-1$
        if (icon != null) {
            cameraAction.putValue(Action.SMALL_ICON, icon);
            cameraAction.putValue(Action.NAME, null);
        }

        anyButtons = true;
        cameraButton = new JButton(cameraAction);
    }

    final JButton refreshButton;
    if (visToolDataProvider == null) {
        refreshButton = null;
    } else {
        anyButtons = true;

        refreshButton = new JButton(Msg.ACTION_REFRESH());

        ImageIcon icon = loadIcon("refresh-24.png"); //$NON-NLS-1$
        if (icon != null) {
            refreshButton.setIcon(icon);
            // don't remove the name
        }

        refreshButton.setForeground(Color.RED);
        refreshButton.setEnabled(false);

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (visToolDataProvider.refreshData()) {
                    refreshButton.setEnabled(false);
                }
            }
        });

        visToolDataProvider.addVisToolDataChangedListener(new VisToolDataChangedListener() {
            @Override
            public void visToolDataChanged(Object source) {
                refreshButton.setEnabled(true);
            }
        });
    }

    VisToolToolBar toolBar = null;

    if (anyButtons) {
        toolBar = new VisToolToolBar(keepOnTop, cameraButton, refreshButton);
        toolBar.setFloatable(floatable);
    }
    return toolBar;

}

From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java

@Override
public void start() {
    startDateTime = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    runStatus = RunStatus.STATUS_RUNNING;

    String selectedFilename = "";

    if (file == null) {
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_LASTLOADPATH) != null) {
            fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                    .getProperties().getProperty(ImageCaptureProperties.KEY_LASTLOADPATH)));
        }/*from   ww w .  j  a  v a2 s.c o  m*/

        int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
        }
    }

    if (file != null) {
        log.debug("Selected file to load: " + file.getName() + ".");

        if (file.exists() && file.isFile() && file.canRead()) {
            // Save location
            Singleton.getSingletonInstance().getProperties().getProperties()
                    .setProperty(ImageCaptureProperties.KEY_LASTLOADPATH, file.getPath());
            selectedFilename = file.getName();

            String[] headers = new String[] {};

            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
            int rows = 0;
            try {
                rows = readRows(file, csvFormat);
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error loading csv format, trying tab delimited: ").append(e.getMessage())
                        .append("\n");
                log.debug(e.getMessage());
                try {
                    // try reading as tab delimited format, if successful, use that format.
                    CSVFormat tabFormat = CSVFormat.newFormat('\t').withIgnoreSurroundingSpaces(true)
                            .withHeader(headers).withQuote('"');
                    rows = readRows(file, tabFormat);
                    csvFormat = tabFormat;
                } catch (IOException e1) {
                    errors.append("Error Loading data: ").append(e1.getMessage()).append("\n");
                    log.error(e.getMessage(), e1);
                }
            }

            try {
                Reader reader = new FileReader(file);

                CSVParser csvParser = new CSVParser(reader, csvFormat);

                Map<String, Integer> csvHeader = csvParser.getHeaderMap();
                headers = new String[csvHeader.size()];
                int i = 0;
                for (String header : csvHeader.keySet()) {
                    headers[i++] = header;
                    log.debug(header);
                }

                boolean okToRun = true;
                //TODO: Work picking/checking responsibility into a FieldLoaderWizard
                List<String> headerList = Arrays.asList(headers);
                if (!headerList.contains("barcode")) {
                    log.error("Input file " + file.getName()
                            + " header does not contain required field 'barcode'.");
                    // no barcode field, we can't match the input to specimen records.
                    errors.append("Field \"barcode\" not found in csv file headers.  Unable to load data.")
                            .append("\n");
                    okToRun = false;
                }

                if (okToRun) {

                    Iterator<CSVRecord> iterator = csvParser.iterator();

                    FieldLoader fl = new FieldLoader();

                    if (headerList.size() == 3 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")) {
                        log.debug("Input file matches case 1: Unclassified text only.");
                        // Allowed case 1a: unclassified text only

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }
                    } else if (headerList.size() == 4 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimClusterIdentifier")) {
                        log.debug(
                                "Input file matches case 1: Unclassified text only (with cluster identifier).");
                        // Allowed case 1b: unclassified text only (including cluster identifier)

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    String verbatimClusterIdentifier = record.get("verbatimClusterIdentifier");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, verbatimClusterIdentifier,
                                            questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else if (headerList.size() == 8 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimLocality") && headerList.contains("verbatimDate")
                            && headerList.contains("verbatimNumbers")
                            && headerList.contains("verbatimCollector")
                            && headerList.contains("verbatimCollection")) {
                        // Allowed case two, transcription into verbatim fields, must be exact list of all
                        // verbatim fields, not including cluster identifier or other metadata.
                        log.debug("Input file matches case 2: Full list of verbatim fields.");

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatim fields.",
                                "Verbatim Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {

                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimLocality = record.get("verbatimLocality");
                                    String verbatimDate = record.get("verbatimDate");
                                    String verbatimCollector = record.get("verbatimCollector");
                                    String verbatimCollection = record.get("verbatimCollection");
                                    String verbatimNumbers = record.get("verbatimNumbers");
                                    String verbatimUnclasifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimLocality, verbatimDate, verbatimCollector,
                                            verbatimCollection, verbatimNumbers, verbatimUnclasifiedText,
                                            questions);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else {
                        // allowed case three, transcription into arbitrary sets verbatim or other fields
                        log.debug("Input file case 3: Arbitrary set of fields.");

                        // Check column headers before starting run.
                        boolean headersOK = false;

                        try {
                            HeaderCheckResult headerCheck = fl.checkHeaderList(headerList);
                            if (headerCheck.isResult()) {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Confirm load from file " + selectedFilename + " (" + rows
                                                + " rows) with headers: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            } else {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Problem found with headers in file, try to load anyway?\nHeaders: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Problem in fields for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            }
                        } catch (LoadException e) {
                            errors.append("Error loading data: \n").append(e.getMessage()).append("\n");
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    e.getMessage().replaceAll(":", ":\n"), "Error Loading Data: Problem Fields",
                                    JOptionPane.ERROR_MESSAGE);

                            log.error(e.getMessage(), e);
                        }

                        if (headersOK) {
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                Map<String, String> data = new HashMap<String, String>();
                                CSVRecord record = iterator.next();
                                String barcode = record.get("barcode");
                                Iterator<String> hi = headerList.iterator();
                                boolean containsNonVerbatim = false;
                                while (hi.hasNext()) {
                                    String header = hi.next();
                                    // Skip any fields prefixed by the underscore character _
                                    if (!header.equals("barcode") && !header.startsWith("_")) {
                                        data.put(header, record.get(header));
                                        if (!header.equals("questions")
                                                && MetadataRetriever.isFieldExternallyUpdatable(Specimen.class,
                                                        header)
                                                && MetadataRetriever.isFieldVerbatim(Specimen.class, header)) {
                                            containsNonVerbatim = true;
                                        }
                                    }
                                }
                                if (data.size() > 0) {
                                    try {
                                        boolean updated = false;
                                        if (containsNonVerbatim) {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_CLASSIFIED, true);
                                        } else {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_VERBATIM, true);
                                        }
                                        counter.incrementSpecimens();
                                        if (updated) {
                                            counter.incrementSpecimensUpdated();
                                        }
                                    } catch (HibernateException e1) {
                                        // Catch (should just be development) problems with the underlying query 
                                        StringBuilder message = new StringBuilder();
                                        message.append("Query Error loading row (").append(lineNumber)
                                                .append(")[").append(barcode).append("]")
                                                .append(e1.getMessage());
                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e1.getMessage(), e1,
                                                RunnableJobError.TYPE_LOAD_FAILED);
                                        counter.appendError(err);
                                        log.error(e1.getMessage(), e1);

                                    } catch (LoadException e) {
                                        StringBuilder message = new StringBuilder();
                                        message.append("Error loading row (").append(lineNumber).append(")[")
                                                .append(barcode).append("]").append(e.getMessage());

                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e.getMessage(), e,
                                                RunnableJobError.TYPE_LOAD_FAILED);

                                        counter.appendError(err);
                                        // errors.append(message.append("\n").toString());
                                        log.error(e.getMessage(), e);
                                    }
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            String message = "Can't load data, problem with headers.";
                            errors.append(message).append("\n");
                            log.error(message);
                        }
                    }
                }
                csvParser.close();
                reader.close();
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error Loading data: ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            }
        }

    } else {
        //TODO: handle error condition
        log.error("File selection cancelled by user.");
    }

    report(selectedFilename);
    done();
}

From source file:com.mirth.connect.client.ui.AttachmentExportDialog.java

private void browseSelected() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    if (userPreferences != null) {
        File currentDir = new File(userPreferences.get("currentDirectory", ""));

        if (currentDir.exists()) {
            chooser.setCurrentDirectory(currentDir);
        }/*from ww w .j  a v a  2 s . c o  m*/
    }

    if (chooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
        if (userPreferences != null) {
            userPreferences.put("currentDirectory", chooser.getCurrentDirectory().getPath());
        }

        fileField.setText(chooser.getSelectedFile().getAbsolutePath());
    }
}

From source file:net.menthor.editor.v2.util.Util.java

public static File chooseFile(Component parent, String lastPath, String dialogTitle, String fileDescription,
        String fileExtension, boolean checkOverrideFile) throws IOException {
    JFileChooser fileChooser = createChooser(lastPath, checkOverrideFile);
    fileChooser.setDialogTitle(dialogTitle);
    FileNameExtensionFilter filter = new FileNameExtensionFilter(fileDescription, fileExtension);
    fileChooser.addChoosableFileFilter(filter);
    if (SystemUtil.onWindows())
        fileChooser.setFileFilter(filter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    if (fileChooser.showDialog(parent, "Ok") == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (!file.getName().endsWith("." + fileExtension)) {
            file = new File(file.getCanonicalFile() + "." + fileExtension);
        } else {/*from  w  ww.  jav  a  2 s. c o  m*/
            file = new File(file.getCanonicalFile() + "");
        }
        return file;
    } else {
        return null;
    }
}

From source file:coreferenceresolver.gui.MarkupGUI.java

public MarkupGUI() throws IOException {
    highlightPainters = new ArrayList<>();

    for (int i = 0; i < COLORS.length; ++i) {
        DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(
                COLORS[i]);//from  w  ww  . j a va2s .  c  om
        highlightPainters.add(highlightPainter);
    }

    defaulPath = FileUtils.readFileToString(new File(".\\src\\coreferenceresolver\\gui\\defaultpath"));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());

    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    //create menu items
    JMenuItem importMenuItem = new JMenuItem("Import");

    JMenuItem exportMenuItem = new JMenuItem("Export");

    fileMenu.add(importMenuItem);
    fileMenu.add(exportMenuItem);

    menuBar.add(fileMenu);

    this.setJMenuBar(menuBar);

    ScrollablePanel mainPanel = new ScrollablePanel();
    mainPanel.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.NONE);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    //IMPORT BUTTON
    importMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //                MarkupGUI.reviewElements.clear();
            //                MarkupGUI.markupReviews.clear();                
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose your markup file");
            markupFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException, BadLocationException {
                        readMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath());
                        for (int i = 0; i < markupReviews.size(); ++i) {
                            mainPanel.add(newReviewPanel(markupReviews.get(i), i));
                        }
                        return null;
                    }

                    protected void done() {
                        MarkupGUI.this.revalidate();
                        d.dispose();
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    //EXPORT BUTTON: GET NEW VALUE (REF, TYPE) OF NPs      
    exportMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose where your markup file saved");
            markupFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException {
                        for (Review review : markupReviews) {
                            generateNPsRef(review);
                        }
                        int i = 0;
                        for (ReviewElement reviewElement : reviewElements) {
                            int j = 0;
                            for (Element element : reviewElement.elements) {
                                String newType = element.typeSpinner.getValue().toString();
                                if (newType.equals("Object")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(0);
                                } else if (newType.equals("Attribute")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(3);
                                } else if (newType.equals("Other")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(1);
                                } else if (newType.equals("Candidate")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(2);
                                }
                                ++j;
                            }
                            ++i;
                        }
                        initMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath() + File.separator
                                + "markup.out.txt");
                        return null;
                    }

                    protected void done() {
                        d.dispose();
                        try {
                            Desktop.getDesktop()
                                    .open(new File(markupFileChooser.getSelectedFile().getAbsolutePath()));
                        } catch (IOException ex) {
                            Logger.getLogger(MarkupGUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    JScrollPane scrollMainPane = new JScrollPane(mainPanel);
    scrollMainPane.getVerticalScrollBar().setUnitIncrement(16);
    scrollMainPane.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
    scrollMainPane.setSize(this.getWidth(), this.getHeight());
    this.setResizable(false);
    this.add(scrollMainPane, BorderLayout.CENTER);
    this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    this.pack();
}

From source file:net.pandoragames.far.ui.swing.menu.FileMenu.java

private void init(final Localizer localizer, final ComponentRepository componentRepository) {
    //   Import/*from  w ww  .  j av a 2 s. c  o m*/
    JMenuItem importMenu = new JMenuItem(localizer.localize("label.import"));
    importMenu.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser(config.getFileListExportDirectory());
            fileChooser.setDialogTitle(localizer.localize("label.select-import-file"));
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = fileChooser.showOpenDialog(FileMenu.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                Runnable fileImporter = new ImportAction(fileChooser.getSelectedFile(), localizer,
                        componentRepository.getOperationCallBackListener(), config.isWindows());
                Thread thread = new Thread(fileImporter);
                thread.setDaemon(true);
                thread.start();
            }
        }
    });
    this.add(importMenu);
    //   Export
    export = new JMenuItem(localizer.localize("label.export"));
    export.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ExportFileListDialog dialog = new ExportFileListDialog(mainFrame, tableModel, config);
            dialog.pack();
            dialog.setVisible(true);
        }
    });
    this.add(export);
    // seperator 
    this.addSeparator();
    //   Edit
    edit = new JMenuItem(localizer.localize("label.edit"));
    edit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileEditor editor = new FileEditor(mainFrame, tableModel.getSelectedRows().get(0), config);
            editor.pack();
            editor.setVisible(true);
        }
    });
    this.add(edit);
    //   View
    JMenuItem view = new JMenuItem(viewAction);
    this.add(view);
    //   Preview
    JMenuItem preview = new JMenuItem(previewAction);
    this.add(preview);
    //   Info
    info = new JMenuItem(localizer.localize("label.info"));
    info.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            InfoView infoView = new InfoView(mainFrame, tableModel.getSelectedRows().get(0), config,
                    repository);
            infoView.pack();
            infoView.setVisible(true);
        }
    });
    this.add(info);
    // seperator 
    this.addSeparator();
    // copy
    copy = new JMenuItem(localizer.localize("menu.copy"));
    copy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.copyDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(copy);
    // tree copy
    treeCopy = new JMenuItem(localizer.localize("menu.treeCopy"));
    treeCopy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.treeCopyDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(treeCopy);
    // move
    move = new JMenuItem(localizer.localize("menu.move"));
    move.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.moveDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(move);
    // delete
    delete = new JMenuItem(localizer.localize("menu.delete"));
    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.deleteDialog(tableModel, findForm.getBaseDirectory(), errorSink, config,
                    mainFrame);
        }
    });
    this.add(delete);
    // rename
    rename = new JMenuItem(localizer.localize("menu.rename-dialog"));
    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowIndex = tableModel.getRowIndex(tableModel.getSelectedRows().get(0));
            FileOperationDialog.renameDialog(rowIndex, tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(rename);
}