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.itd.dbmrgdao.TestTime7.java

@Ignore
@org.junit.Test/*from w  w  w. java2 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, scdate = null, p1Start = null, p1End = null, p2Start = null, p2End = null,
                otStart = null, otEnd = null;
        String scode = "1985";
        StringBuilder insertSQL = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p2end) VALUES ");

        StringBuilder deleteSQL = new StringBuilder("DELETE FROM scandata WHERE (sc_sysid,scdate) IN (");

        // read from select file
        for (strLine = br.readLine(); strLine != null; strLine = br.readLine()) {
            System.out.println(strLine);
        }

        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])) {

                deleteSQL = deleteSQL.append(" ('").append(sysid).append("','").append(scdate).append("'),");

                insertSQL = insertSQL.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");
            }
        }

        deleteSQL = deleteSQL.append(" ('").append(sysid).append("','").append(scdate).append("'))");

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

        scanDao.executeSQL(deleteSQL.toString());

        scanDao.executeSQL(insertSQL.toString());

        br.close();

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

}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopFileMultiUploadField.java

public DesktopFileMultiUploadField() {
    fileUploading = AppBeans.get(FileUploadingAPI.NAME);

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);

    DesktopResources resources = App.getInstance().getResources();
    Messages messages = AppBeans.get(Messages.NAME);
    String caption = messages.getMessage(getClass(), "upload.selectFiles");
    impl = new JButton();
    impl.setAction(new AbstractAction(caption, resources.getIcon(DEFAULT_ICON)) {
        @Override// w  w w  .  j a va 2s  .  c o m
        public void actionPerformed(ActionEvent e) {
            if (fileChooser.showOpenDialog(impl) == JFileChooser.APPROVE_OPTION) {
                processFiles(fileChooser.getSelectedFiles());
            }
        }
    });
    DesktopComponentsHelper.adjustSize(impl);
}

From source file:de.ep3.ftpc.controller.portal.CrawlerDownloadController.java

@Override
public void mouseClicked(MouseEvent e) {
    CrawlerResultsItem.PreviewPanel previewPanel = (CrawlerResultsItem.PreviewPanel) e.getSource();
    CrawlerResult crawlerResult = previewPanel.getCrawlerResult();
    CrawlerFile crawlerFile = crawlerResult.getFile();

    FTPClient ftpClient = crawlerResult.getFtpClient();

    if (ftpClient.isConnected()) {
        JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadWhileConnected"), null,
                JOptionPane.ERROR_MESSAGE);
        return;/*  ww  w  .  j  av a2s .  c  om*/
    }

    String fileExtension = crawlerFile.getExtension();

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter chooserFilter = new FileNameExtensionFilter(
            i18n.translate("fileType", fileExtension.toUpperCase()), crawlerFile.getExtension());

    chooser.setApproveButtonText(i18n.translate("buttonSave"));
    chooser.setDialogTitle(i18n.translate("fileDownloadTo"));
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    chooser.setFileFilter(chooserFilter);
    chooser.setSelectedFile(new File(crawlerFile.getName()));

    int selection = chooser.showSaveDialog(portalFrame);

    if (selection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = chooser.getSelectedFile();

        Server relatedServer = crawlerResult.getServer();

        try {
            ftpClient.connect(relatedServer.need("server.ip"),
                    Integer.parseInt(relatedServer.need("server.port")));

            int replyCode = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new IOException(i18n.translate("crawlerServerRefused"));
            }

            if (relatedServer.has("user.name")) {
                String userName = relatedServer.get("user.name");
                String userPassword = "";

                if (relatedServer.hasTemporary("user.password")) {
                    userPassword = relatedServer.getTemporary("user.password");
                }

                boolean loggedIn = ftpClient.login(userName, userPassword);

                if (!loggedIn) {
                    throw new IOException(i18n.translate("crawlerServerAuthFail"));
                }
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            /* Download file */

            InputStream is = ftpClient.retrieveFileStream(crawlerFile.getFullName());

            if (is != null) {

                byte[] rawFile = new byte[(int) crawlerFile.getSize()];

                int i = 0;

                while (true) {
                    int b = is.read();

                    if (b == -1) {
                        break;
                    }

                    rawFile[i] = (byte) b;
                    i++;

                    /* Occasionally update the download progress */

                    if (i % 1024 == 0) {
                        int progress = Math.round((((float) i) / crawlerFile.getSize()) * 100);

                        status.add(i18n.translate("crawlerDownloadProgress", progress));
                    }
                }

                is.close();
                is = null;

                if (!ftpClient.completePendingCommand()) {
                    throw new IOException();
                }

                Files.write(fileToSave.toPath(), rawFile);
            }

            /* Logout and disconnect */

            ftpClient.logout();

            tryDisconnect(ftpClient);

            status.add(i18n.translate("crawlerDownloadDone"));
        } catch (IOException ex) {
            tryDisconnect(ftpClient);

            JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadFailed", ex.getMessage()),
                    null, JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:AST.DesignPatternDetection.java

private void btPathFinderActionPerformed(ActionEvent e) {
    // TODO add your code here
    JFileChooser f = new JFileChooser();
    f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    f.showDialog(null, null);/*from w  w  w . j a  v  a  2  s.co  m*/
    tfPath.setText(f.getSelectedFile().toString());

    vertices.clear();
    dugumler.clear();
    methods.clear();

    //System.out.println(f.getCurrentDirectory());
    //System.out.println(f.getSelectedFile());
}

From source file:Result3.java

public void createImage() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("Documents"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try {/*w w w.  jav a2s.co  m*/
            ImageIO.write(bImage1, "png", new File(chooser.getSelectedFile() + ".png"));
        } catch (IOException ex) {
            Logger.getLogger(Result1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:PreferencesTest.java

public PreferencesFrame() {
    // get position, size, title from preferences

    Preferences root = Preferences.userRoot();
    final Preferences node = root.node("/com/horstmann/corejava");
    int left = node.getInt("left", 0);
    int top = node.getInt("top", 0);
    int width = node.getInt("width", DEFAULT_WIDTH);
    int height = node.getInt("height", DEFAULT_HEIGHT);
    setBounds(left, top, width, height);

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);//w ww .  j  ava  2 s  .  co  m

    // set up file chooser that shows XML files

    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    // accept all files ending with .xml
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
        }

        public String getDescription() {
            return "XML files";
        }
    });

    // set up menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem exportItem = new JMenuItem("Export preferences");
    menu.add(exportItem);
    exportItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                    node.exportSubtree(out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem importItem = new JMenuItem("Import preferences");
    menu.add(importItem);
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    InputStream in = new FileInputStream(chooser.getSelectedFile());
                    Preferences.importPreferences(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            node.putInt("left", getX());
            node.putInt("top", getY());
            node.putInt("width", getWidth());
            node.putInt("height", getHeight());
            node.put("title", getTitle());
            System.exit(0);
        }
    });
}

From source file:org.pgptool.gui.ui.tools.browsefs.ExistingFileChooserDialog.java

private JFileChooser buildFileChooserDialog() {
    JFileChooser ofd = new JFileChooser();
    ofd.setFileSelectionMode(JFileChooser.FILES_ONLY);
    ofd.setAcceptAllFileFilterUsed(true);
    ofd.setMultiSelectionEnabled(false);
    ofd.setDialogTitle(Messages.get("action.chooseExistingFile"));
    ofd.setApproveButtonText(Messages.get("action.choose"));
    suggestInitialDirectory(ofd);//from  w  w  w.ja  v  a2 s.  c  o  m
    doFileChooserPostConstruct(ofd);
    return ofd;
}

From source file:FileChooserTest.java

public ImageViewerFrame() {
    setTitle("FileChooserTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // set up menu bar
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);// www .j a va  2s  .  c o m

    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem openItem = new JMenuItem("Open");
    menu.add(openItem);
    openItem.addActionListener(new FileOpenListener());

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });

    // use a label to display the images
    label = new JLabel();
    add(label);

    // set up file chooser
    chooser = new JFileChooser();

    // accept all image files ending with .jpg, .jpeg, .gif
    /*
    final ExtensionFileFilter filter = new ExtensionFileFilter();
    filter.addExtension("jpg");
    filter.addExtension("jpeg");
    filter.addExtension("gif");
    filter.setDescription("Image files");
    */
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
    chooser.setFileFilter(filter);

    chooser.setAccessory(new ImagePreviewer(chooser));

    chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
}

From source file:XMLWriteTest.java

public XMLWriteFrame() {
    setTitle("XMLWriteTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    chooser = new JFileChooser();

    // add component to frame

    comp = new RectangleComponent();
    add(comp);// ww  w  .java 2s  .  c om

    // set up menu bar

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem newItem = new JMenuItem("New");
    menu.add(newItem);
    newItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            comp.newDrawing();
        }
    });

    JMenuItem saveItem = new JMenuItem("Save with DOM/XSLT");
    menu.add(saveItem);
    saveItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                saveDocument();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(XMLWriteFrame.this, e.toString());
            }
        }
    });

    JMenuItem saveStAXItem = new JMenuItem("Save with StAX");
    menu.add(saveStAXItem);
    saveStAXItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                saveStAX();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(XMLWriteFrame.this, e.toString());
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });
}

From source file:org.pgptool.gui.ui.tools.browsefs.MultipleFilesChooserDialog.java

private JFileChooser buildFileChooserDialog() {
    JFileChooser ofd = new JFileChooser();
    ofd.setFileSelectionMode(JFileChooser.FILES_ONLY);
    ofd.setAcceptAllFileFilterUsed(true);
    ofd.setMultiSelectionEnabled(true);// w ww . j ava 2  s  .com
    ofd.setDialogTitle(Messages.get("action.chooseExistingFile"));
    ofd.setApproveButtonText(Messages.get("action.choose"));
    suggestInitialDirectory(ofd);
    doFileChooserPostConstruct(ofd);
    return ofd;
}