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:de.codesourcery.jasm16.ide.ui.views.ProjectConfigurationView.java

@Override
protected JPanel getPanel() {
    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());

    // project name
    int y = 0;/*from  w ww . j  av  a 2s  . c  om*/
    GridBagConstraints cnstrs = constraints(0, y, false, false, GridBagConstraints.NONE);
    result.add(new JLabel("Project name"), cnstrs);

    cnstrs = constraints(1, y++, true, false, GridBagConstraints.NONE);
    result.add(projectName, cnstrs);

    // build options panel
    final JPanel buildOptionsPanel = new JPanel();
    buildOptionsPanel.setLayout(new GridBagLayout());

    buildOptionsPanel.setBorder(BorderFactory.createTitledBorder("Build options"));

    cnstrs = constraints(0, 0, false, false, GridBagConstraints.NONE);
    buildOptionsPanel.add(new JLabel("Compilation root"), cnstrs);

    cnstrs = constraints(1, 0, false, false, GridBagConstraints.NONE);
    compilationRootName.setEditable(false);
    compilationRootName.setColumns(25);
    buildOptionsPanel.add(compilationRootName, cnstrs);

    cnstrs = constraints(2, 0, true, false, GridBagConstraints.NONE);
    buildOptionsPanel.add(compilationRootButton, cnstrs);

    compilationRootButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser chooser;
            File baseDir = null;
            if (project != null) {
                baseDir = project.getConfiguration().getBaseDirectory();
            }
            if (StringUtils.isNotBlank(compilationRootName.getText())) {
                File tmp = new File(compilationRootName.getText()).getParentFile();
                if (tmp.exists() && tmp.isDirectory()) {
                    baseDir = tmp;
                }
            }
            if (baseDir != null) {
                chooser = new JFileChooser(baseDir);
            } else {
                chooser = new JFileChooser();
            }
            final int result = chooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile().isFile()) {
                compilationRootName.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        }
    });

    // generate self-relocating code ?
    cnstrs = constraints(0, 1, false, false, GridBagConstraints.NONE);
    buildOptionsPanel.add(new JLabel("Generate self-relocating code?"), cnstrs);

    cnstrs = constraints(1, 1, true, true, GridBagConstraints.NONE);
    cnstrs.gridwidth = 2;
    buildOptionsPanel.add(generateSelfRelocatingCode, cnstrs);

    // inline short literals ?
    cnstrs = constraints(0, 2, false, false, GridBagConstraints.NONE);
    buildOptionsPanel.add(new JLabel("Inline short literals?"), cnstrs);

    cnstrs = constraints(1, 2, true, true, GridBagConstraints.NONE);
    cnstrs.gridwidth = 2;
    buildOptionsPanel.add(inlineShortLiterals, cnstrs);

    // add build options panel to parent
    cnstrs = constraints(0, y++, true, false, GridBagConstraints.BOTH);
    cnstrs.gridwidth = 2;
    result.add(buildOptionsPanel, cnstrs);

    // buttons
    final JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridBagLayout());

    cnstrs = constraints(0, 0, false, false, GridBagConstraints.NONE);
    buttonPanel.add(saveButton, cnstrs);
    saveButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (hasValidInput()) {
                onSave();
            }
        }
    });

    cnstrs = constraints(1, 0, true, true, GridBagConstraints.NONE);
    buttonPanel.add(cancelButton, cnstrs);
    cancelButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            onCancel();
        }
    });

    // button panel
    cnstrs = constraints(0, y++, true, true, GridBagConstraints.NONE);
    cnstrs.gridwidth = 2;
    result.add(buttonPanel, cnstrs);

    return result;
}

From source file:net.liuxuan.device.VACVBS.JIF_DrawChart_vacvbs.java

public void openFiletoCurve() throws NumberFormatException {
    String tempstr = jFormattedTextField_temp.getText();
    int tempint = Integer.parseInt(tempstr);
    dropinterval = tempint;/*from  ww  w  .j a v a  2s. c  o  m*/

    //??
    //??0?1
    filterds = new double[dropinterval];

    SimpleDateFormat sdfx = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]");
    //        String content;
    String fileContent = null;

    JFileChooser jfc = initFileChooser();
    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        //            String filepath = jfc.getSelectedFile().getAbsolutePath();
        if (jfc.getSelectedFile() == null) {
            //
            System.out.println("!!");
            return;
        }
        try {
            fileContent = Files.toString(jfc.getSelectedFile(), Charsets.ISO_8859_1);

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

    //??,dropinterval
    parseFileToDataStructure(fileContent, 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", metadatas.size()));
    }

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

    tsNotifyFalse();//?

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

        ts_LP.addOrUpdate(new Millisecond(data.date1), data.LP);
        ts_HP.addOrUpdate(new Millisecond(data.date1), data.HP);
        ts_temprature.addOrUpdate(new Millisecond(data.date1), data.Temprature);
        //??100??100
        ts_humidity.addOrUpdate(new Millisecond(data.date1), data.Humidity);
        //25????25
        ts_num.addOrUpdate(new Millisecond(data.date1), data.num);
        //38????38
        ts_time.addOrUpdate(new Millisecond(data.date1), data.Time);
        //?
        //status 1?? 2 ? 3 4 5?? 6 7?? 8 9? 0 
        ts_reserved1.addOrUpdate(new Millisecond(data.date1), data.reserved1);
        ts_reserved2.addOrUpdate(new Millisecond(data.date1), data.reserved2);
        ts_reserved3.addOrUpdate(new Millisecond(data.date1), data.reserved3);
    }

    tsNotifyTrue();//
}

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

public File chooseFile(boolean forSave) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int ret = forSave ? chooser.showSaveDialog(getMainFrame()) : chooser.showOpenDialog(getMainFrame());
    if (JFileChooser.APPROVE_OPTION == ret) {
        File file = chooser.getSelectedFile();
        return file;
    }/*from   w ww . jav a2 s  .c o m*/
    return null;
}

From source file:io.gameover.utilities.pixeleditor.Pixelizer.java

public void openFile() {
    JFileChooser fc = new JFileChooser();
    int ret = fc.showOpenDialog(this);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {//from w  ww .  j  a  v  a2 s.  c o m
            BufferedImage image = ImageIO.read(fc.getSelectedFile());
            if (image.getHeight() > Frame.NB_PIXELS || image.getWidth() % Frame.NB_PIXELS != 0
                    || image.getHeight() != Frame.NB_PIXELS) {
                int retOption = JOptionPane.showConfirmDialog(this,
                        "Image seems not a pixel image (height > " + Frame.NB_PIXELS
                                + "px or length not a multiple of " + Frame.NB_PIXELS
                                + "). Would you like to convert it to pixel?");
                if (retOption == JOptionPane.OK_OPTION) {
                    convertToPixelImage(image);
                }
            } else {
                openImage(image);
            }
            refreshCurrentColors();
            savedStates.clear();
            currentStateIndex = 0;
            clearSelection();
            refresh();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:de.quadrillenschule.azocamsyncd.astromode.gui.AstroModeJPanel.java

private void chooseDirjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseDirjButtonActionPerformed
    JFileChooser jfc = new JFileChooser(astroFolderjTextField.getText());
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        astroFolderjTextField.setText(jfc.getSelectedFile().getAbsolutePath());
    }/*from  ww  w .  java 2 s .c  o m*/
}

From source file:it.staiger.jmeter.protocol.http.config.gui.DynamicFilePanel.java

/**
 * opens a dialog box to choose a file and returns selected file's
 * folder./*from  w  ww.ja v  a2 s .c  o  m*/
 *
 * @return a new File object of selected folder
 */
private String browseAndGetFolderPath() {
    String path = folder.getText();
    if (path.isEmpty())
        path = FileDialoger.getLastJFCDirectory();
    JFileChooser chooser = new JFileChooser(new File(path));

    chooser.setDialogTitle("select folder");// $NON-NLS-1$
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    if (chooser.showOpenDialog(GuiPackage.getInstance().getMainFrame()) == JFileChooser.APPROVE_OPTION) {
        path = chooser.getSelectedFile().getAbsolutePath();
        FileDialoger.setLastJFCDirectory(path);
    }
    return path;
}

From source file:analysis.postRun.PostRunWindow.java

/**
 * Method which opens a file chooser so the user can select a log to view.
 */// w ww  .j  av  a  2  s . c o  m
//   void chooseFile()
//   {
//      JFileChooser fc = new JFileChooser();
//      fc.setDialogTitle("Select Log");
//      fc.setCurrentDirectory(new File(System.getProperty("user.dir") + "/log"));
//      fc.setAcceptAllFileFilterUsed(false);
//      FileFilter filter = new FileNameExtensionFilter(" file", "csv");
//      fc.addChoosableFileFilter(filter);
//      int rVal = fc.showOpenDialog(null);
//
//      if (rVal == JFileChooser.APPROVE_OPTION)
//      {
//         currFile = fc.getSelectedFile().getAbsolutePath();
//         //System.out.println(currFile);
//         parent=fc.getSelectedFile().getParent();
//         System.out.println(parent);
//         getData(fc.getSelectedFile().getAbsolutePath());
//      }
//      else {
//         System.exit(0);
//      }
//   }

//dialogTitle="select log"
//directoryPath="/log"
//allFileFilterUsed=false
//description= "file"
//FileNameExtensionFilter
//extension = "csv"
//FileFilter filter = new FileNameExtensionFilter(" file", "csv");
void chooseFile1() {
    JFileChooser fc = GUIFileReader.getFileChooser("Select Log", "/log",
            new FileNameExtensionFilter(" file", "csv"));

    int rVal = fc.showOpenDialog(null);

    if (rVal == JFileChooser.APPROVE_OPTION) {
        currFile = fc.getSelectedFile().getAbsolutePath();
        //System.out.println(currFile);
        parent = fc.getSelectedFile().getParent();
        System.out.println(parent);
        getData(fc.getSelectedFile().getAbsolutePath());
    } else {
        System.exit(0);
    }
}

From source file:bio.gcat.gui.BDATool.java

public boolean openFile() {
    JFileChooser chooser = new FileNameExtensionFileChooser(BDA_EXTENSION_FILTER);
    chooser.setDialogTitle("Open");
    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
        return false;

    return openFile(chooser.getSelectedFile());
}

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

/**
 * @param baseDir/*from w  ww  .j  a va2 s . com*/
 * @return
 */
public Vector<Pair<String, String>> findOldL10NKeys(final String[] fileNames) {
    initLucene(true);

    //if (srcCodeFilesDir == null)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (srcCodeFilesDir != null) {
            chooser.setSelectedFile(new File(FilenameUtils.getName(srcCodeFilesDir.getAbsolutePath())));
            chooser.setSelectedFile(new File(srcCodeFilesDir.getParent()));
        }

        if (chooser.showOpenDialog(UIRegistry.getMostRecentWindow()) == JFileChooser.APPROVE_OPTION) {
            srcCodeFilesDir = new File(chooser.getSelectedFile().getAbsolutePath());
        } else {
            return null;
        }
    }

    indexSourceFiles();

    Vector<Pair<String, String>> fullNotFoundList = new Vector<Pair<String, String>>();

    try {
        ConversionLogger convLogger = new ConversionLogger();
        convLogger.initialize("resources", "Resources");

        for (String fileName : fileNames) {
            Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>();

            Vector<String> terms = new Vector<String>();

            String propFileName = baseDir.getAbsolutePath() + "/" + fileName;

            File resFile = new File(propFileName + ".properties");
            if (resFile.exists()) {
                List<?> lines = FileUtils.readLines(resFile);
                for (String line : (List<String>) lines) {
                    if (!line.startsWith("#")) {
                        int inx = line.indexOf("=");
                        if (inx > -1) {
                            String[] toks = StringUtils.split(line, "=");
                            if (toks.length > 1) {
                                terms.add(toks[0]);
                            }
                        }
                    }
                }
            } else {
                System.err.println("Doesn't exist: " + resFile.getAbsolutePath());
            }

            String field = "contents";
            QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer);

            for (String term : terms) {
                Query query;
                try {
                    if (term.equals("AND") || term.equals("OR"))
                        continue;

                    query = parser.parse(term);

                    String subTerm = null;
                    int hits = getTotalHits(query, 10);
                    if (hits == 0) {
                        int inx = term.indexOf('.');
                        if (inx > -1) {
                            subTerm = term.substring(inx + 1);
                            hits = getTotalHits(parser.parse(subTerm), 10);

                            if (hits == 0) {
                                int lastInx = term.lastIndexOf('.');
                                if (lastInx > -1 && lastInx != inx) {
                                    subTerm = term.substring(lastInx + 1);
                                    hits = getTotalHits(parser.parse(subTerm), 10);
                                }
                            }
                        }
                    }

                    if (hits == 0 && !term.endsWith("_desc")) {
                        notFoundList.add(new Pair<String, String>(term, subTerm));

                        log.debug("'" + term + "' was not found "
                                + (subTerm != null ? ("SubTerm[" + subTerm + "]") : ""));
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            String fullName = propFileName + ".html";
            TableWriter tblWriter = convLogger.getWriter(FilenameUtils.getName(fullName), propFileName);
            tblWriter.startTable();
            tblWriter.logHdr("Id", "Full Key", "Sub Key");
            int cnt = 1;
            for (Pair<String, String> pair : notFoundList) {
                tblWriter.log(Integer.toString(cnt++), pair.first,
                        pair.second != null ? pair.second : "&nbsp;");
            }
            tblWriter.endTable();

            fullNotFoundList.addAll(notFoundList);

            if (notFoundList.size() > 0 && resFile.exists()) {
                List<String> lines = (List<String>) FileUtils.readLines(resFile);
                Vector<String> linesCache = new Vector<String>();

                for (Pair<String, String> p : notFoundList) {
                    linesCache.clear();
                    linesCache.addAll(lines);

                    int lineInx = 0;
                    for (String line : linesCache) {
                        if (!line.startsWith("#")) {
                            int inx = line.indexOf("=");
                            if (inx > -1) {
                                String[] toks = StringUtils.split(line, "=");
                                if (toks.length > 1) {
                                    if (toks[0].equals(p.first)) {
                                        lines.remove(lineInx);
                                        break;
                                    }
                                }
                            }
                        }
                        lineInx++;
                    }
                }
                FileUtils.writeLines(resFile, linesCache);
            }

        }
        convLogger.closeAll();

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerSearchHelper.class, ex);
        ex.printStackTrace();
    }

    return fullNotFoundList;
}

From source file:net.sf.nmedit.nomad.core.Nomad.java

public void fileOpen() {
    // todo keep working directory
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    FileServiceTool.addChoosableFileFilters(chooser);
    if (!(chooser.showOpenDialog(mainWindow) == JFileChooser.APPROVE_OPTION))
        return;//w w w  .  j a  v  a2  s . c  om
    final File[] selected = chooser.getSelectedFiles();
    final FileService service = FileServiceTool.lookupFileService(chooser);

    if (service == null) {
        JOptionPane.showMessageDialog(mainWindow, "Could not find service to open file.");
        return;
    }
    Runnable run = new Runnable() {
        public void run() {
            for (File file : selected) {
                service.open(file);
            }
        }
    };
    SwingUtilities.invokeLater(WorkIndicator.create(getWindow(), run));
}