Example usage for javax.swing JFileChooser JFileChooser

List of usage examples for javax.swing JFileChooser JFileChooser

Introduction

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

Prototype

public JFileChooser() 

Source Link

Document

Constructs a JFileChooser pointing to the user's default directory.

Usage

From source file:com.simplexrepaginator.RepaginateFrame.java

protected JButton createInputButton() {
    JButton b = new JButton("Click or drag to set input files", PDF_1342);

    b.setHorizontalTextPosition(SwingConstants.RIGHT);
    b.setIconTextGap(25);/*from   w w w  .  j  a v a2  s.c  om*/

    b.setTransferHandler(new InputButtonTransferHandler());

    b.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(true);
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            if (chooser.showOpenDialog(RepaginateFrame.this) != JFileChooser.APPROVE_OPTION)
                return;
            setInput(Arrays.asList(chooser.getSelectedFiles()));
            if (JOptionPane.showConfirmDialog(RepaginateFrame.this, "Use input paths as output paths?",
                    "Use Input As Output?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                setOutput(new ArrayList<File>(repaginator.getInputFiles()));
            }
        }
    });

    return b;
}

From source file:it.ferogrammer.ui.MainAppFrame.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    if (jPanel2.getComponentCount() == 1 && (jPanel2.getComponent(0) instanceof ElectropherogramChartPanel)) {
        ElectropherogramChartPanel chartPanel = (ElectropherogramChartPanel) jPanel2.getComponent(0);
        final JFileChooser fc = new JFileChooser();
        //            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(chartPanel);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (!file.getName().endsWith(".png")) {
                int extindex = file.getPath().indexOf('.') == -1 ? file.getPath().length()
                        : file.getPath().indexOf('.');
                file = new File(file.getPath().substring(0, extindex) + ".png");
            }//from   ww w  .j a  va 2 s.c  o  m
            try {
                ChartUtilities.saveChartAsPNG(file, chartPanel.getChart(), chartPanel.getWidth(),
                        chartPanel.getHeight());
            } catch (IOException ex) {
                JOptionPane op = new JOptionPane();
                op.showMessageDialog(jPanel2, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane op = new JOptionPane();
        op.showMessageDialog(jPanel2, "Cannot export image", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:ca.canucksoftware.clockthemebuilder.ThemeBuilderView.java

private File loadFileChooser(javax.swing.filechooser.FileFilter ff, String saveName) {
    File result;/*  w w  w . java2 s .c  o  m*/
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    fc.setMultiSelectionEnabled(false);
    if (ff != null) {
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(ff);
    } else {
        fc.setAcceptAllFileFilterUsed(true);
    }
    if (saveName == null) {
        fc.setDialogTitle("");
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    } else {
        fc.setDialogTitle("Save As...");
        fc.setSelectedFile(new File(saveName));
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    }
    return result;
}

From source file:forge.gui.ImportDialog.java

@SuppressWarnings("serial")
public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) {
    this.forcedSrcDir = forcedSrcDir;

    _topPanel = new FPanel(new MigLayout("insets dialog, gap 0, center, wrap, fill"));
    _topPanel.setOpaque(false);//from   w w w .  j a  va2 s.com
    _topPanel.setBackgroundTexture(FSkin.getIcon(FSkinProp.BG_TEXTURE));

    isMigration = !StringUtils.isEmpty(forcedSrcDir);

    // header
    _topPanel.add(new FLabel.Builder().text((isMigration ? "Migrate" : "Import") + " profile data").fontSize(15)
            .build(), "center");

    // add some help text if this is for the initial data migration
    if (isMigration) {
        final FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill"));
        blurbPanel.setOpaque(false);
        final JPanel blurbPanelInterior = new JPanel(
                new MigLayout("insets dialog, gap 10, center, wrap, fill"));
        blurbPanelInterior.setOpaque(false);
        blurbPanelInterior.add(new FLabel.Builder().text("<html><b>What's this?</b></html>").build(),
                "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder()
                .text("<html>Over the last several years, people have had to jump through a lot of hoops to"
                        + " update to the most recent version.  We hope to reduce this workload to a point where a new"
                        + " user will find that it is fairly painless to update.  In order to make this happen, Forge"
                        + " has changed where it stores your data so that it is outside of the program installation directory."
                        + "  This way, when you upgrade, you will no longer need to import your data every time to get things"
                        + " working.  There are other benefits to having user data separate from program data, too, and it"
                        + " lays the groundwork for some cool new features.</html>")
                .build(), "growx, w 50:50:");
        blurbPanelInterior.add(
                new FLabel.Builder().text("<html><b>So where's my data going?</b></html>").build(),
                "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder().text(
                "<html>Forge will now store your data in the same place as other applications on your system."
                        + "  Specifically, your personal data, like decks, quest progress, and program preferences will be"
                        + " stored in <b>" + ForgeConstants.USER_DIR
                        + "</b> and all downloaded content, such as card pictures,"
                        + " skins, and quest world prices will be under <b>" + ForgeConstants.CACHE_DIR
                        + "</b>.  If, for whatever"
                        + " reason, you need to set different paths, cancel out of this dialog, exit Forge, and find the <b>"
                        + ForgeConstants.PROFILE_TEMPLATE_FILE
                        + "</b> file in the program installation directory.  Copy or rename" + " it to <b>"
                        + ForgeConstants.PROFILE_FILE
                        + "</b> and edit the paths inside it.  Then restart Forge and use"
                        + " this dialog to move your data to the paths that you set.  Keep in mind that if you install a future"
                        + " version of Forge into a different directory, you'll need to copy this file over so Forge will know"
                        + " where to find your data.</html>")
                .build(), "growx, w 50:50:");
        blurbPanelInterior.add(new FLabel.Builder().text(
                "<html><b>Remember, your data won't be available until you complete this step!</b></html>")
                .build(), "growx, w 50:50:");

        final FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        blurbPanel.add(blurbScroller, "hmin 150, growy, growx, center, gap 0 0 5 5");
        _topPanel.add(blurbPanel, "gap 10 10 20 0, growy, growx, w 50:50:");
    }

    // import source widgets
    final JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10"));
    importSourcePanel.setOpaque(false);
    importSourcePanel.add(new FLabel.Builder().text("Import from:").build());
    _txfSrc = new FTextField.Builder().readonly().build();
    importSourcePanel.add(_txfSrc, "pushx, growx");
    _btnChooseDir = new FLabel.ButtonBuilder().text("Choose directory...").enabled(!isMigration).build();
    final JFileChooser _fileChooser = new JFileChooser();
    _fileChooser.setMultiSelectionEnabled(false);
    _fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    _btnChooseDir.setCommand(new UiCommand() {
        @Override
        public void run() {
            // bring up a file open dialog and, if the OK button is selected, apply the filename
            // to the import source text field
            if (JFileChooser.APPROVE_OPTION == _fileChooser.showOpenDialog(JOptionPane.getRootFrame())) {
                final File f = _fileChooser.getSelectedFile();
                if (!f.canRead()) {
                    FOptionPane.showErrorDialog("Cannot access selected directory (Permission denied).");
                } else {
                    _txfSrc.setText(f.getAbsolutePath());
                }
            }
        }
    });
    importSourcePanel.add(_btnChooseDir, "h pref+8!, w pref+12!");

    // add change handler to the import source text field that starts up a
    // new analyzer.  it also interacts with the current active analyzer,
    // if any, to make sure it cancels out before the new one is initiated
    _txfSrc.getDocument().addDocumentListener(new DocumentListener() {
        boolean _analyzerActive; // access synchronized on _onAnalyzerDone
        String prevText;

        private final Runnable _onAnalyzerDone = new Runnable() {
            @Override
            public synchronized void run() {
                _analyzerActive = false;
                notify();
            }
        };

        @Override
        public void removeUpdate(final DocumentEvent e) {
        }

        @Override
        public void changedUpdate(final DocumentEvent e) {
        }

        @Override
        public void insertUpdate(final DocumentEvent e) {
            // text field is read-only, so the only time this will get updated
            // is when _btnChooseDir does it
            final String text = _txfSrc.getText();
            if (text.equals(prevText)) {
                // only restart the analyzer if the directory has changed
                return;
            }
            prevText = text;

            // cancel any active analyzer
            _cancel = true;

            if (!text.isEmpty()) {
                // ensure we don't get two instances of this function running at the same time
                _btnChooseDir.setEnabled(false);

                // re-disable the start button.  it will be enabled if the previous analyzer has
                // already successfully finished
                _btnStart.setEnabled(false);

                // we have to wait in a background thread since we can't block in the GUI thread
                final SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        // wait for active analyzer (if any) to quit
                        synchronized (_onAnalyzerDone) {
                            while (_analyzerActive) {
                                _onAnalyzerDone.wait();
                            }
                        }
                        return null;
                    }

                    // executes in gui event loop thread
                    @Override
                    protected void done() {
                        _cancel = false;
                        synchronized (_onAnalyzerDone) {
                            // this will populate the panel with data selection widgets
                            final _AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone,
                                    isMigration);
                            analyzer.run();
                            _analyzerActive = true;
                        }
                        if (!isMigration) {
                            // only enable the directory choosing button if this is not a migration dialog
                            // since in that case we're permanently locked to the starting directory
                            _btnChooseDir.setEnabled(true);
                        }
                    }
                };
                analyzerStarter.execute();
            }
        }
    });
    _topPanel.add(importSourcePanel, "gaptop 20, pushx, growx");

    // prepare import selection panel (will be cleared and filled in later by an analyzer)
    _selectionPanel = new JPanel();
    _selectionPanel.setOpaque(false);
    _topPanel.add(_selectionPanel, "growx, growy, gaptop 10");

    // action button widgets
    final Runnable cleanup = new Runnable() {
        @Override
        public void run() {
            SOverlayUtils.hideOverlay();
        }
    };
    _btnStart = new FButton("Start import");
    _btnStart.setEnabled(false);
    _btnCancel = new FButton("Cancel");
    _btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            _cancel = true;
            cleanup.run();
            if (null != onDialogClose) {
                onDialogClose.run();
            }
        }
    });

    final JPanel southPanel = new JPanel(new MigLayout("ax center"));
    southPanel.setOpaque(false);
    southPanel.add(_btnStart, "center, w pref+144!, h pref+12!");
    southPanel.add(_btnCancel, "center, w pref+144!, h pref+12!, gap 72");
    _topPanel.add(southPanel, "growx");
}

From source file:cn.labthink.ReadAccess060.java

private void jButton_OpenfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OpenfileActionPerformed

    //filter//from  ww  w .  ja  v a 2s.  co m
    ExtensionFileFilter filter = new ExtensionFileFilter("mdb", false, true);
    filter.setDescription("Open DataBase File");
    //?

    JFileChooser jfc = new JFileChooser();

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

    jfc.setDialogTitle("Choose the mdb file");
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.OPEN_DIALOG);
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setFileFilter(filter);
    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        String filesrc = jfc.getSelectedFile().getAbsolutePath();
        inputfile = jfc.getSelectedFile();
        jLabel_dbpath.setText("DB File Path:" + filesrc);
        maxid = Integer.MIN_VALUE;
        minid = Integer.MAX_VALUE;
    } else {
        return;
    }
    //

    Infodata = new Vector();
    Infocolumns = new Vector();

    try {

        //            String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D://b.MDB";
        if (inputfile == null) {
            return;
        }
        initDB();

        sql = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = sql.executeQuery("SELECT * FROM test order by testid desc");

        Infocolumns.add("TestID");
        Infocolumns.add("TestType");
        Infocolumns.add("DeviceID");
        Infocolumns.add("CellID");
        Infocolumns.add("Operator");
        Infocolumns.add("StartTime");
        Infocolumns.add("EndTime");
        Infocolumns.add("Comments");
        Infocolumns.add("SetTemp.");
        int columnCount = Infocolumns.size();
        Vector row;
        while (rs.next()) {
            row = new Vector(columnCount);
            int temp = 0;
            int ivalue = rs.getInt("TESTID");
            maxid = maxid < ivalue ? ivalue : maxid;
            minid = minid > ivalue ? ivalue : minid;
            row.add(ivalue);
            temp = rs.getInt("TESTTYPE");
            if (temp == 1) {
                row.add("OTR");
            } else if (temp == 2) {
                row.add("WVTR");
            } else {
                row.add(temp);
            }
            row.add(rs.getInt("DEVICEID"));
            row.add(rs.getString("CELLID"));
            row.add(rs.getString("OPERATOR"));
            row.add(rs.getDate("STARTTIME"));
            row.add(rs.getDate("ENDTIME"));
            row.add(rs.getString("COMMENTS"));
            row.add(rs.getDouble("SETTEMP"));
            //                row.add(rs.getString(11));
            //                row.add(rs.getInt(10));
            Infodata.add(row);
        }

        DefaultTableModel tableModel = new DefaultTableModel(Infodata, Infocolumns);
        jTable1.setModel(tableModel);
        //?  
        // jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
        jTable1.setSelectionBackground(Color.orange);
        //?
        TableRowSorter<TableModel> tableRowSorter = new TableRowSorter<TableModel>(tableModel);
        jTable1.setRowSorter(tableRowSorter);
        //            jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// table
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// ??
        jTable1.setDefaultRenderer(Object.class, tcr);

        //
        ((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer())
                .setHorizontalAlignment(SwingConstants.CENTER);
        //            DefaultTableCellRenderer  rh = new DefaultTableCellRenderer();
        //            rh.setHorizontalAlignment(SwingConstants.CENTER);
        //            jTable1.getTableHeader().setDefaultRenderer(rh);

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(28);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(7).setPreferredWidth(100);

    } catch (SQLException ee) {
        System.out.println(ee);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ReadAccess060.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            sql.close();
        } catch (Exception e) {
        }
        try {
            rs.close();
        } catch (Exception e) {
        }
    }

    //        validate();

}

From source file:cn.labthink.ReadAccess330.java

private void jButton_OpenfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OpenfileActionPerformed

    //filter//  w  ww  .  ja  v  a  2  s  . c  om
    ExtensionFileFilter filter = new ExtensionFileFilter("mdb", false, true);
    filter.setDescription("Open DataBase File");
    //?

    JFileChooser jfc = new JFileChooser();

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

    jfc.setDialogTitle("Choose the mdb file");
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.OPEN_DIALOG);
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setFileFilter(filter);
    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        String filesrc = jfc.getSelectedFile().getAbsolutePath();
        inputfile = jfc.getSelectedFile();
        jLabel_dbpath.setText("DB File Path:" + filesrc);
        maxid = Integer.MIN_VALUE;
        minid = Integer.MAX_VALUE;
    } else {
        return;
    }
    //

    Infodata = new Vector();
    Infocolumns = new Vector();

    try {

        //            String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D://b.MDB";
        if (inputfile == null) {
            return;
        }
        initDB();

        sql = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = sql.executeQuery("SELECT * FROM test order by testid desc");

        Infocolumns.add("TestID");
        Infocolumns.add("TestType");
        Infocolumns.add("DeviceID");
        Infocolumns.add("CellID");
        Infocolumns.add("Operator");
        Infocolumns.add("StartTime");
        Infocolumns.add("EndTime");
        Infocolumns.add("Comments");
        Infocolumns.add("SetTemp.");
        int columnCount = Infocolumns.size();
        Vector row;
        while (rs.next()) {
            row = new Vector(columnCount);
            int temp = 0;
            int ivalue = rs.getInt("TESTID");
            maxid = maxid < ivalue ? ivalue : maxid;
            minid = minid > ivalue ? ivalue : minid;
            row.add(ivalue);
            temp = rs.getInt("TESTTYPE");
            if (temp == 1) {
                row.add("OTR");
            } else if (temp == 2) {
                row.add("WVTR");
            } else {
                row.add(temp);
            }
            row.add(rs.getInt("DEVICEID"));
            row.add(rs.getString("CELLID"));
            row.add(rs.getString("OPERATOR"));
            row.add(rs.getDate("STARTTIME"));
            row.add(rs.getDate("ENDTIME"));
            row.add(rs.getString("COMMENTS"));
            row.add(rs.getDouble("SETTEMP"));
            //                row.add(rs.getString(11));
            //                row.add(rs.getInt(10));
            Infodata.add(row);
        }

        DefaultTableModel tableModel = new DefaultTableModel(Infodata, Infocolumns);
        jTable1.setModel(tableModel);
        //?  
        // jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
        jTable1.setSelectionBackground(Color.orange);
        //?
        TableRowSorter<TableModel> tableRowSorter = new TableRowSorter<TableModel>(tableModel);
        jTable1.setRowSorter(tableRowSorter);
        //            jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// table
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// ??
        jTable1.setDefaultRenderer(Object.class, tcr);

        //
        ((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer())
                .setHorizontalAlignment(SwingConstants.CENTER);
        //            DefaultTableCellRenderer  rh = new DefaultTableCellRenderer();
        //            rh.setHorizontalAlignment(SwingConstants.CENTER);
        //            jTable1.getTableHeader().setDefaultRenderer(rh);

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(28);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(7).setPreferredWidth(100);

    } catch (SQLException ee) {
        System.out.println(ee);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ReadAccess330.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            sql.close();
        } catch (Exception e) {
        }
        try {
            rs.close();
        } catch (Exception e) {
        }
    }

    //        validate();

}

From source file:biz.wolschon.finance.jgnucash.panels.TaxReportPanel.java

/**
 * Show a dialog to export// ww  w  .  j  a  va  2 s  . com
 * a CSV-file that contains the
 * shown {@link TransactionSum}s
 * for each month, year or day.
 */
protected void showExportCSVDialog() {
    JFileChooser fc = new JFileChooser();
    fc.setAcceptAllFileFilterUsed(true);
    fc.addChoosableFileFilter(new FileFilter() {

        @Override
        public boolean accept(final File aF) {
            return aF.isDirectory() || aF.getName().endsWith(".csv");
        }

        @Override
        public String getDescription() {
            return "CSV-file";
        }
    });
    int dialogResult = fc.showSaveDialog(this);
    if (dialogResult != JFileChooser.APPROVE_OPTION) {
        return;
    }
    File file = fc.getSelectedFile();
    if (file.exists()) {
        int confirmation = JOptionPane.showConfirmDialog(this, "File exists. Replace file?");
        if (confirmation != JOptionPane.YES_OPTION) {
            showExportCSVDialog();
            return;
        }
    }
    ExportGranularities gran = (ExportGranularities) myExportGranularityCombobox.getSelectedItem();
    try {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        exportCSV(file, gran);
    } finally {
        setCursor(Cursor.getDefaultCursor());
    }
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientIDConversionFactory.java

private String getKey() {
    String path = null;/*from ww  w  . j  a  va2  s.  c o m*/
    String key = UserInfoBean.getInstance().getKey();
    if (key == null) {
        if ((path = getNoteKeyDrive()) == null) {
            Object[] possibleValues = { "Type in the key", "Browse to find the file containing the key" };
            String selectedValue = (String) JOptionPane.showInputDialog(null,
                    "You have selected an item associated with a report\n"
                            + "which contains protected health information.\n"
                            + "You need a decryption key to perform this operation.\n"
                            + "How would you like to enter the key?\n"
                            + "(If the key is on a floppy disk, insert the disk then\n select "
                            + "\"Browse to find the file containing the key\")",
                    "Notes Viewer", JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[0]);
            if (selectedValue == null) {
                return "Not a valid key";
            }
            if (selectedValue.equalsIgnoreCase("Type in the key")) {
                key = JOptionPane.showInputDialog(this, "Please input the decryption key");
                if (key == null) {
                    return "Not a valid key";
                }
            } else {
                JFileChooser chooser = new JFileChooser();
                int returnVal = chooser.showOpenDialog(null);
                if (returnVal == JFileChooser.CANCEL_OPTION) {
                    return "Not a valid key";
                }

                File f = null;
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    f = chooser.getSelectedFile();
                    System.out.println("Open this file: " + f.getAbsolutePath());

                    BufferedReader in = null;
                    try {
                        in = new BufferedReader(new FileReader(f.getAbsolutePath()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            if (line.length() > 0) {
                                key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } else {
            System.out.println("Found key file: " + path);
            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(path));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.length() > 0) {
                        key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    if (key == null) {
        return null;
    } else {
        UserInfoBean.getInstance().setKey(key);
    }
    return key;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.area.AreaDoseResponseController.java

/**
 * Ask user to choose for a directory and invoke swing worker for creating
 * PDF report/*from w ww  .ja v  a  2  s  .  co m*/
 *
 * @throws IOException
 */
protected void createPdfReport() throws IOException {
    Experiment experiment = areaMainController.getExperiment();
    // choose directory to save pdf file
    JFileChooser chooseDirectory = new JFileChooser();
    chooseDirectory.setDialogTitle("Choose a directory to save the report");
    chooseDirectory.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooseDirectory.setSelectedFile(new File("Dose Response Report " + experiment.toString() + " - "
            + experiment.getProject().toString() + ".pdf"));
    // in response to the button click, show open dialog
    int returnVal = chooseDirectory.showSaveDialog(areaMainController.getDataAnalysisPanel());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File directory = chooseDirectory.getCurrentDirectory();
        DoseResponseReportSwingWorker doseResponseReportSwingWorker = new DoseResponseReportSwingWorker(
                directory, chooseDirectory.getSelectedFile().getName());
        doseResponseReportSwingWorker.execute();
    } else {
        areaMainController.showMessage("Open command cancelled by user", "", JOptionPane.INFORMATION_MESSAGE);
    }
}

From source file:com.jtk.pengelolaanujian.view.dosenpengampu.UploadNilai.java

private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    int result = fileChooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        url = fileChooser.getSelectedFile().getAbsolutePath();
        textUrl.setText(url);//from  w  w  w .j  a  va 2 s .c o  m
    }
}