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:cc.creativecomputing.io.CCIOUtil.java

/**
 * Opens a platform-specific file chooser dialog to select a file for input. This function returns the full path to
 * the selected file as a <b>String</b>, or <b>null</b> if no selection. Files are filtered according to the given
 * file extensions.//from ww  w .ja  v  a2 s.  c o m
 * 
 * @webref input:files
 * @param theExtensions file extensions for filtering
 * @return full path to the selected file, or null if canceled.
 * 
 * @see #selectOutput(String)
 * @see #selectFolder(String)
 */
static public String selectFilteredInput(String... theExtensions) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new CCFileExtensionFilter(theExtensions));
    fileChooser.setDialogTitle("Select a file...");

    int returned = fileChooser.showOpenDialog(null);
    if (returned == JFileChooser.CANCEL_OPTION) {
        selectedFile = null;
    } else {
        selectedFile = fileChooser.getSelectedFile();
    }
    return (selectedFile == null) ? null : selectedFile.getAbsolutePath();
}

From source file:org.fhcrc.cpl.toolbox.gui.chart.PanelWithChart.java

/**
 * Add two new menu items to the popup menu, for saving to TSV and CSV files
 *//* www .  j a  v  a  2s  . co  m*/
protected void initPopupMenu() {
    addSeparatorToPopupMenu();

    //TSV
    JMenuItem saveTSVMenuItem = new JMenuItem(TextProvider.getText("SAVE_DATA_AS_TSV"));
    saveTSVMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JFileChooser fc = new JFileChooser();
            int chooserStatus = fc.showOpenDialog(PanelWithChart.this);
            //if user didn't hit OK, ignore
            if (chooserStatus != JFileChooser.APPROVE_OPTION)
                return;

            File outFile = fc.getSelectedFile();
            saveChartDataToTSV(outFile);
        }
    });
    addItemToPopupMenu(saveTSVMenuItem);

    //CSV
    JMenuItem saveCSVMenuItem = new JMenuItem(TextProvider.getText("SAVE_DATA_AS_CSV"));
    saveCSVMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JFileChooser wfc = new JFileChooser();
            int chooserStatus = wfc.showOpenDialog(PanelWithChart.this);
            //if user didn't hit OK, ignore
            if (chooserStatus != JFileChooser.APPROVE_OPTION)
                return;

            File outFile = wfc.getSelectedFile();
            saveChartDataToCSV(outFile);
        }
    });
    addItemToPopupMenu(saveCSVMenuItem);
}

From source file:com.itd.dbmrgdao.TestTime4.java

@Ignore
@org.junit.Test//  ww w  . j  av a2  s. c  o m
public void test() throws ParseException {
    String newTab = "\t";
    String[] sysidLine;

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();

    String filename = f.getAbsolutePath();
    try {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);
        String strLine;

        String sysid = null, scdate = null, p1Start = null, p1End = null, p2Start = null, p2End = null,
                otStart = null, otEnd = null;

        StringBuilder mySql = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p1end,p2start,p2end,otstart,otend) VALUES (?,?,?,?,?,?,?,?,?)");

        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            if (sysid != null && !sysid.equals(parts[0])) {
                mySql = mySql.append(", (").append(sysid).append(",\"1985\"").append(",").append(scdate)
                        .append(",").append(p1Start).append(",").append(p1End).append(",").append(p2Start)
                        .append(",").append(p2End).append(",").append(otStart).append(",").append(otEnd)
                        .append(")");

                //                    if (p1Start != null || p2End != null) {
                //                        ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
                //                        p1Start = scanRule.getP1start();
                //                        p2End = scanRule.getP2end();
                //                    }
                //                    ScanDataTest scanData = new ScanDataTest(sysid, scdate, p1Start, p2End);

                p1Start = null;
                p2End = null;

            }

            sysid = parts[0];
            scdate = parts[1];

            if (parts[6].equals("01")) {
                p1Start = CompareTime(p1Start, parts[5], "01");
            } else {
                p2End = CompareTime(p2End, parts[5], "04");
            }

        }

        //last line
        //            if (p1Start != null || p2End != null) {
        //                ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
        //                p1Start = scanRule.getP1start();
        //                p2End = scanRule.getP2end();
        //            }
        //            ScanDataTest scanData = new ScanDataTest(sysid, scdate, p1Start, p2End);
        //            System.out.println(scanData);
        br.close();

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, e);

    }

}

From source file:edu.umich.robot.GuiApplication.java

/**
 * <p>//from ww  w . j  a  v  a2s  .com
 * Firing up this application requires a configuration file. If no
 * configuration file is presented on the command line, this is called to
 * prompt the user to select a configuration file.
 * 
 * <p>
 * Future work should probably include some default instead of doing this.
 * 
 * @return The selected, loaded configuration file.
 */
public static Config promptForConfig(Component parent) {

    System.out.println("CLASSPATH: " + System.getenv("CLASSPATH"));
    System.out.println("DYLD_LIBRARY_PATH: " + System.getenv("DYLD_LIBRARY_PATH"));
    System.out.println("LD_LIBRARY_PATH: " + System.getenv("LD_LIBRARY_PATH"));
    System.out.println("SOAR_HOME: " + System.getenv("SOAR_HOME"));
    System.out.println("java.library.path: " + System.getProperty("java.library.path"));

    JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter filter = new FileNameExtensionFilter("Text Config File", "txt");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    int ret = fc.showOpenDialog(parent);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            return new ConfigFile(fc.getSelectedFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
    return null;
}

From source file:modelibra.swing.app.util.FileSelector.java

/**
 * Gets the opened file given a file path.
 * /*from   www.  ja  va  2  s .  com*/
 * @param path
 *            path
 * @param lang
 *            language
 * @return file
 */
public File getOpenFile(String path, NatLang lang) {
    File selectedFile = null;
    File currentFile = null;
    if (path != null && !path.equalsIgnoreCase("?")) {
        currentFile = new File(path);
    } else
        currentFile = lastOpenedFile;

    JFileChooser chooser = new JFileChooser();
    chooser.setLocale(lang.getLocale());
    if (currentFile != null) {
        chooser.setCurrentDirectory(currentFile);
    }
    int returnVal = chooser.showOpenDialog(chooser);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
    }
    lastOpenedFile = selectedFile;

    return selectedFile;
}

From source file:com.itd.dbmrgdao.TestTime3_backup.java

@Ignore
@org.junit.Test/*from  ww  w . j  av  a2 s . c  om*/
public void test() throws ParseException {
    String newTab = "\t";
    String[] sysidLine;

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();

    String filename = f.getAbsolutePath();
    try {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);
        String strLine;

        String sysid = null, p1Start = null, p1End = null, p2Start = null, p2End = null, otStart = null,
                otEnd = null;
        Date scdate = null;

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {
                // rule if whatever employee register will get standard hour 8 hrs
                if (p1Start != null || p2End != null) {
                    ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
                    p1Start = scanRule.getP1start();
                    p2End = scanRule.getP2end();
                }

                // set up data in entity
                ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
                ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart,
                        otEnd);
                // remove old record (key is sysid and scdate)
                gennericDao.remove(scanData);
                gennericDao.create(scanData);

                //clear 
                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            sysid = parts[0];
            scdate = new SimpleDateFormat("yyyyMMdd", Locale.US).parse(parts[1]);

            if (parts[6].equals("01")) {
                p1Start = CompareTime(p1Start, parts[5], "01");
            } else {
                p2End = CompareTime(p2End, parts[5], "04");
            }

        }
        //last line

        if (p1Start != null || p2End != null) {
            ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
            p1Start = scanRule.getP1start();
            p2End = scanRule.getP2end();
        }

        ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
        ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart, otEnd);
        gennericDao.remove(scanData);
        gennericDao.create(scanData);

        br.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

From source file:com.itd.dbmrgdao.TestTime6.java

@Ignore
@org.junit.Test//from w w w  .ja  v  a2s .co  m
public void test() throws ParseException {
    String newTab = "\t";
    String[] sysidLine;

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();

    String fileName = f.getAbsolutePath();
    try {
        FileReader reader = new FileReader(fileName);
        BufferedReader br = new BufferedReader(reader);
        String strLine;

        String sysid = null, scdate = null, p1Start = null, p1End = null, p2Start = null, p2End = null,
                otStart = null, otEnd = null;
        String scode = "1985";
        StringBuilder mySql = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p2end) VALUES ");

        //             StringBuilder mySql = new StringBuilder(
        //                    "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p1end,p2start,p2end,otstart,otend) VALUES ");

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {
                mySql = mySql.append(" ('").append(sysid).append("','").append(scode).append("','")
                        .append(scdate).append("','").append(p1Start).append("','").append(p2End).append("'),");

                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            //clear 
            sysid = parts[0];
            scdate = new StringBuffer(parts[1]).insert(parts[1].length() - 2, "-").toString();
            scdate = new StringBuffer(scdate).insert(scdate.length() - 5, "-").toString();

            String timeString = new StringBuffer(parts[5]).insert(parts[5].length() - 2, ":").toString();

            if (parts[6].equals("01")) {
                p1Start = CompareTime(p1Start, timeString, "01");
            } else {
                p2End = CompareTime(p2End, timeString, "04");
            }
        }

        mySql = mySql.append(" ('").append(sysid).append("','").append(scode).append("','").append(scdate)
                .append("','").append(p1Start).append("','").append(p2End).append("')");

        scanDao.executeSQL(mySql.toString());

        br.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

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

@Override
public void performAction() {
    this.executeInjection();
    JFileChooser chooser = vista.getFileChooserApriXMLAndTGD();
    File file;//from ww w  .j  a  v a 2  s  .c om
    int returnVal = chooser.showOpenDialog(WindowManager.getDefault().getMainWindow());
    Scenario scenario = null;
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        String fileAbsoluteFile = file.getPath();
        scenario = openCompositionFile(fileAbsoluteFile, file, true);
        MappingTask mappingTask = scenario.getMappingTask();
        File f = chooser.getSelectedFile();
        FileObject fo = FileUtil.toFileObject(f);
        //            TGDDataObject dobj = null;
        try {
            TGDEditorSupport tGDEditorSupport = new TGDEditorSupport(fo);
            //                dobj = tGDEditorSupport.getDataObject();
            tGDEditorSupport.open();
            //giannisk
            scenario.setTGDEditor(tGDEditorSupport);
            scenario.getMappingTaskTopComponent().requestActive();
            //    dobj = DataObject.find(fo);
        } catch (DataObjectNotFoundException ex) {
            ex.printStackTrace();
        }
        //if (dobj != null){
        //    OpenCookie lc = (OpenCookie)dobj.getCookie(OpenCookie.class);
        //    if (lc == null) {/* cannot do it */ return;}
        //    lc.open();
        ////    Line l = lc.getLineSet().getOriginal(lineNumber);
        ////    l.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
        //}

        //try {
        //    Editor.getDefaultLocale().
        ////    new ROEditor(fo).open();
        //    
        //    new TGDEditorSupport(fo).edit();
        //    
        ////    DataObject dataObject = new ROEditor(fo).getDataObject();
        ////
        ////    EditorCookie cookie = (EditorCookie)dataObject.getCookie(EditorCookie.class);
        ////    cookie.open();
        //    
        //    System.out.println("eseguito");
        //} catch (DataObjectNotFoundException e) {
        //    e.printStackTrace();
        //}
        // 
        if (!(mappingTask.getSourceProxy() instanceof ConstantDataSourceProxy)) {
            //                Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
            scenario.setCompositionTopComponent(new CompositionTopComponent(scenario));
            actionComposition.performAction();
        }
    }
}

From source file:org.pmedv.jake.commands.AddFilesCommand.java

@Override
public void execute() {

    final ApplicationContext ctx = AppContext.getApplicationContext();
    final ApplicationWindow win = (ApplicationWindow) ctx.getBean(BeanDirectory.WINDOW_APPLICATION);

    /**//from w ww . j  a v a2 s.c o m
     * Get last selected folder to simplify file browsing
     */

    if (AppContext.getLastSelectedFolder() == null)
        AppContext.setLastSelectedFolder(System.getProperty("user.home"));

    JFileChooser fc = new JFileChooser(AppContext.getLastSelectedFolder());
    fc.setDialogTitle("Add files");
    fc.setMultiSelectionEnabled(true);
    fc.setFileFilter(new MP3Filter());

    int result = fc.showOpenDialog(win);

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    File[] files = fc.getSelectedFiles();

    PlayerView view = JakeUtil.getCurrentActivePlayer();

    if (view == null) {

        ArrayList<File> fileList = new ArrayList<File>();

        for (int i = 0; i < files.length; i++)
            fileList.add(files[i]);

        final PlayerController controller = new PlayerController(fileList);
        JakeUtil.updateRecentFiles(fc.getSelectedFile().getAbsolutePath());
        AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

        View v = new View(fc.getSelectedFile().getAbsolutePath(), null, controller.getPlayerView());

        v.addListener(new DockingWindowAdapter() {

            @Override
            public void windowClosing(DockingWindow arg0) throws OperationAbortedException {

                controller.getPlayer().close();
                controller.getPlayFileCommand().setPlaying(false);
            }

        });

        openEditor(v);
    }

    else {

        if (files.length >= 1) {

            AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());
            JakeUtil.updateRecentFiles(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

            FileTableModel model = (FileTableModel) view.getFileTable().getModel();

            for (int i = 0; i < files.length; i++) {
                model.addObject(files[i]);
            }

        }

    }

}

From source file:com.itd.dbmrgdao.TestTime5.java

@Ignore
@org.junit.Test/*from ww  w  . j av  a 2 s.  c  o m*/
public void test() throws ParseException {
    String newTab = "\t";
    String[] sysidLine;

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();

    String fileName = f.getAbsolutePath();
    try {
        FileReader reader = new FileReader(fileName);
        BufferedReader br = new BufferedReader(reader);
        String strLine;

        String sysid = null, scdate = null, p1Start = null, p1End = null, p2Start = null, p2End = null,
                otStart = null, otEnd = null;

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {

                List<Object> lst = new ArrayList<Object>();

                scanDao.deleteScanDataBySysId_Sdate(sysid, scdate);
                scanDao.insertScanData(sysid, "1985", scdate, p1Start, p1End, p2Start, p2End, otStart, otEnd);

                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            //clear 
            sysid = parts[0];
            scdate = new StringBuffer(parts[1]).insert(parts[1].length() - 2, "-").toString();
            scdate = new StringBuffer(scdate).insert(scdate.length() - 5, "-").toString();

            String timeString = new StringBuffer(parts[5]).insert(parts[5].length() - 2, ":").toString();

            if (parts[6].equals("01")) {
                p1Start = CompareTime(p1Start, timeString, "01");
            } else {
                p2End = CompareTime(p2End, timeString, "04");
            }

        }

        scanDao.deleteScanDataBySysId_Sdate(sysid, scdate);
        scanDao.insertScanData(sysid, "1985", scdate, p1Start, p1End, p2Start, p2End, otStart, otEnd);

        br.close();

        //last line
        //            if (p1Start != null || p2End != null) {
        //                ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
        //                p1Start = scanRule.getP1start();
        //                p2End = scanRule.getP2end();
        //            }
        //            ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
        //            ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart, otEnd);
        //            gennericDao.remove(scanData);
        //            gennericDao.create(scanData);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}