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:org.nekorp.workflow.desktop.view.FormatoProgramacionView.java

private void importarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importarActionPerformed
    try {/*from  w  w w  .  j a  v  a  2s  .  c  om*/
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Hojas de clculo", "xlsx");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        File f = new File(new File(homePath).getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showOpenDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.application.importarArchivo(chooser.getSelectedFile());
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
    } catch (IOException ex) {
        FormatoProgramacionView.LOGGER.error(ex);
    }
}

From source file:com.enderville.enderinstaller.ui.Installer.java

private void chooseTargetMinecraftFolder() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    int opt = chooser.showOpenDialog(getMainPane());
    if (opt == JFileChooser.APPROVE_OPTION) {
        File dir = chooser.getSelectedFile();
        String oldDir = InstallerConfig.getMinecraftFolder();
        InstallerConfig.setMinecraftFolder(dir.getAbsolutePath());
        File mcjar = new File(InstallerConfig.getMinecraftJar());
        if (!mcjar.exists()) {
            JOptionPane.showMessageDialog(getMainPane(),
                    "The installer couldn't find a minecraft installation in the specified folder.\n"
                            + "Restoring minecraft folder to " + oldDir,
                    "Error setting target Minecraft installation", JOptionPane.ERROR_MESSAGE);
            InstallerConfig.setMinecraftFolder(oldDir);
        }// w w w  . j a v a 2s.c o  m
    }

}

From source file:electroStaticUI.ElectroStaticUIContainer.java

private void buildFileMenu() {
    //create Exit menu item
    exitItem = new JMenuItem("Exit");
    exitItem.setMnemonic(KeyEvent.VK_X);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);/*  w w  w  . j  a  va2  s. com*/
        }
    });

    //open
    open = new JMenuItem("Open");
    open.setMnemonic(KeyEvent.VK_P);
    open.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
        }
    });

    //close
    close = new JMenuItem("Close");
    close.setMnemonic(KeyEvent.VK_C);

    //export
    export = new JMenuItem("Export");
    export.setMnemonic(KeyEvent.VK_E);
    export.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            fChooser.setMultiSelectionEnabled(false);
            fChooser.setAcceptAllFileFilterUsed(false);
            FileNameExtensionFilter svgFilter = new FileNameExtensionFilter("Save Vector Plot(svg)", ".svg");
            FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("Save Voltage Surface Plot(png)",
                    ".png");
            fChooser.addChoosableFileFilter(svgFilter);
            fChooser.addChoosableFileFilter(pngFilter);
            fChooser.setFileFilter(svgFilter);
            int status = fChooser.showSaveDialog(rootPane);
            if (status == JFileChooser.APPROVE_OPTION) {
                if (fChooser.getFileFilter() == svgFilter) {
                    try {
                        saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                        Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                                displayPanel.getHeight());
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                } else if (fChooser.getFileFilter() == pngFilter) {
                    try {
                        saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                        Save.saveChart3dToPNG(DefaultValues.get3dChartToSave(), saveAsName);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }
        }
    });

    //save
    save = new JMenuItem("Save");
    save.setMnemonic(KeyEvent.VK_S);
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION) {
                try {
                    System.out.println("Height: " + displayPanel.getWidth());
                    System.out.println("Width: " + displayPanel.getHeight());
                    saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                    Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                            displayPanel.getHeight());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        }
    });

    //saveAs
    saveAs = new JMenuItem("Save As");
    saveAs.setMnemonic(KeyEvent.VK_A);
    saveAs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION)
                try {
                    System.out.println("Height: " + displayPanel.getWidth());
                    System.out.println("Width: " + displayPanel.getHeight());
                    saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                    System.out.println(saveAsName);
                    Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                            displayPanel.getHeight());
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
            try {
                Save.saveChartToSVG(UserInput.getElectricFieldChart(), saveAsName, displayPanel.getWidth(),
                        displayPanel.getHeight());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    //JMenu object for file menu
    fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);

    //fileMenu.add(newFile);
    //fileMenu.add(open);
    //fileMenu.add(close);
    fileMenu.add(export);
    //fileMenu.add(save);
    //fileMenu.add(saveAs);
    fileMenu.add(exitItem);
}

From source file:jgraph.JShow.java

/**
 * a driver for this demo//from   w w w  .  jav a 2 s.  co  m
 */
@SuppressWarnings("serial")
public static void showtest(DirectedOrderedSparseMultigraph<Object, Object> graph) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JShow demo = new JShow(graph);

    JMenu menu = new JMenu("Snapshot");
    menu.add(new AbstractAction("To JPEG") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                demo.writeJPEGImage(file);
            }
        }
    });
    menu.add(new AbstractAction("Print") {
        public void actionPerformed(ActionEvent e) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(demo);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    frame.setJMenuBar(menuBar);
    frame.getContentPane().add(demo);
    frame.pack();
    frame.setVisible(true);
}

From source file:SciTK.Plot.java

/** 
* Save displayed chart as vector graphics 
*///from   w ww.j  a v a 2 s  .c  o  m
public void saveVectorGraphics() {
    Rectangle r = chart_panel.getBounds(); // get size of chart

    // file selection:
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ExtensionFileFilter("SVG", new String[] { "svg,SVG" }));
    fc.addChoosableFileFilter(new ExtensionFileFilter("PS", new String[] { "ps,PS" }));
    fc.addChoosableFileFilter(new ExtensionFileFilter("EPS", new String[] { "eps,EPS" }));
    // remove default option:
    fc.setAcceptAllFileFilterUsed(false);

    // Select a file using the JFileChooser dialog:
    int fc_return = fc.showSaveDialog(Plot.this);

    // if the user actually wants to save:
    if (fc_return == JFileChooser.APPROVE_OPTION) {
        //get the file:
        File save_file = fc.getSelectedFile();
        // and the type of extension (from file chooser)
        String extension = fc.getFileFilter().getDescription();
        try // try/catch for IO errors
        {
            // For each type of extension, check to see if the name includes the
            // correct extension and then save the image to file.
            // Default extension is EPS
            if (extension == "SVG") {
                // sanity check extension:
                if (!save_file.getName().endsWith(".svg") && !save_file.getName().endsWith(".SVG"))
                    save_file = new File(save_file.getAbsolutePath() + ".svg");
                exportChartAsSVG(chart, r, save_file);
            } else if (extension == "PS") {
                // sanity check extension:
                if (!save_file.getName().endsWith(".ps") && !save_file.getName().endsWith(".PS"))
                    save_file = new File(save_file.getAbsolutePath() + ".ps");
                exportChartAsPS(chart, r, save_file, "ps");
            } else {
                // sanity check extension:
                if (!save_file.getName().endsWith(".eps") && !save_file.getName().endsWith(".EPS"))
                    save_file = new File(save_file.getAbsolutePath() + ".eps");
                exportChartAsPS(chart, r, save_file, "eps");
            }
        } catch (IOException e) {
            DialogError emsg = new DialogError(this, " There was an error saving the file."
                    + System.getProperty("line.separator") + e.getMessage());
        }
    }
}

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

private JButton getCargarGPXButton() {
    JButton cargar = new JButton(i18n.getString("window.gpx.button.load"),
            LogicConstants.getIcon("historico_button_cargargpx"));
    cargar.addActionListener(new ActionListener() {

        @Override//from w  w  w. ja v a  2  s.  c  o  m
        public void actionPerformed(ActionEvent e) {
            fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    }
                    return (f.getName().toLowerCase().endsWith(".gpx"));
                }

                @Override
                public String getDescription() {
                    return i18n.getString("window.gpx.filechooser.filter");
                }
            });

            try {
                if (fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION) {
                    cargarGpx(fileChooser.getSelectedFile());
                }
            } catch (Throwable t) {
                log.error("Error al cargar GPX " + t);
                JOptionPane.showMessageDialog(getBasicWindow().getFrame(),
                        i18n.getString("window.gpx.loadError"));
            }
        }
    });
    return cargar;
}

From source file:lu.lippmann.cdb.ext.hydviga.ui.GapsUIUtil.java

private static void addExportPopupMenu(final Instances ds, final ChartPanel cp) {
    cp.addChartMouseListener(new ChartMouseListener() {
        public void chartMouseClicked(ChartMouseEvent e) {
            final JPopupMenu jPopupMenu = new JPopupMenu("feur");
            final JMenuItem mi1 = new JMenuItem("Export as CSV");
            mi1.addActionListener(new ActionListener() {
                @Override//from ww  w . j  a v a2s . co  m
                public void actionPerformed(final ActionEvent e) {
                    final JFileChooser fc = new JFileChooser();
                    fc.setAcceptAllFileFilterUsed(false);
                    final int returnVal = fc.showSaveDialog(cp);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        try {
                            final File file = fc.getSelectedFile();
                            WekaDataAccessUtil.saveInstancesIntoCSVFile(ds, file);
                        } catch (final Exception ee) {
                            ee.printStackTrace();
                        }
                    }
                }
            });
            jPopupMenu.add(mi1);
            jPopupMenu.show(cp, e.getTrigger().getX(), e.getTrigger().getY());
        }

        public void chartMouseMoved(ChartMouseEvent e) {
        }
    });
}

From source file:com.rpgsheet.xcom.PimpMyXcom.java

private static void openXcomPathDialog(Properties appProperties) {
    // display the box to the user
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("PimpMyXcom - Where is X-COM?");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int retCode = fileChooser.showOpenDialog(null);
    // if the user cancelled the dialog, there is nothing we can do
    if (retCode == JFileChooser.CANCEL_OPTION) {
        log.error("User cancel while attempting to locate X-COM.");
        return;//w  w  w  . j a  va2 s  .  com
    }
    // if there was an error, there is nothing we can do
    if (retCode == JFileChooser.ERROR_OPTION) {
        log.error("Error while attempting to locate X-COM: {}", JFileChooser.ERROR_OPTION);
        return;
    }
    // if the user chose a directory, then we have some work to do
    String xcomPath = fileChooser.getSelectedFile().getAbsolutePath();
    File xcomDir = new File(xcomPath);
    if (containsXcom(xcomDir)) {
        // store the path to xcom in the application properties
        appProperties.setProperty("xcom.path", xcomPath);
        // write the updated application properties to disk
        try {
            saveApplicationProperties(appProperties);
        } catch (IOException e) {
            log.error("Unable to store X-COM path in application properties.", e);
            return;
        }
    }
    // if we were unable to find X-COM
    else {
        log.error("User provided location did not contain X-COM.");
        return;
    }
}

From source file:com.emental.mindraider.ui.dialogs.AttachmentJDialog.java

/**
 * Concetructor.//from ww  w .  j  av  a  2 s . c  o m
 * 
 * @param noteResource
 *            The concept resource.
 * @param dragAndDropReference
 *            The drag'n'drop reference.
 */
public AttachmentJDialog(ConceptResource conceptResource, DragAndDropReference dragAndDropReference) {

    super(Messages.getString("AttachmentJDialog.title"));
    this.conceptResource = conceptResource;
    getContentPane().setLayout(new BorderLayout());
    JPanel p, pp;

    p = new JPanel();
    p.setLayout(new BorderLayout());
    JLabel intro = new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.introduction")
            + "&nbsp;&nbsp;<br><br></html>");
    p.add(intro, BorderLayout.NORTH);
    p.add(new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.description") + "</html>"),
            BorderLayout.CENTER);
    description = new JTextField(38);
    pp = new JPanel(new FlowLayout(FlowLayout.LEFT));
    pp.add(description);
    p.add(pp, BorderLayout.SOUTH);
    getContentPane().add(p, BorderLayout.NORTH);

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.setBorder(new TitledBorder(Messages.getString("AttachmentJDialog.resource")));

    ButtonGroup attachType = new ButtonGroup();

    JPanel webPanel = new JPanel();
    webPanel.setLayout(new BorderLayout());
    webType = new JRadioButton(Messages.getString("AttachmentJDialog.web"));
    webType.setActionCommand(WEB);
    webType.addActionListener(this);
    webType.setSelected(true);
    attachType.add(webType);
    webPanel.add(webType, BorderLayout.NORTH);
    urlTextField = new JTextField("http://", 35);
    urlTextField.selectAll();
    urlTextField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                attach();
            }
        }

        public void keyReleased(KeyEvent keyEvent) {
        }

        public void keyTyped(KeyEvent keyEvent) {
        }
    });
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    p.add(urlTextField);
    webPanel.add(p, BorderLayout.SOUTH);
    mainPanel.add(webPanel, BorderLayout.NORTH);

    JPanel localPanel = new JPanel();
    localPanel.setLayout(new BorderLayout());
    JRadioButton localType = new JRadioButton(Messages.getString("AttachmentJDialog.local"));
    localType.setActionCommand(LOCAL);
    localType.addActionListener(this);
    localPanel.add(localType, BorderLayout.NORTH);
    pathTextField = new JTextField(35);
    pathTextField.setEnabled(false);
    browseButton = new JButton(Messages.getString("AttachmentJDialog.browse"));
    browseButton.setToolTipText(Messages.getString("AttachmentJDialog.browseTip"));
    browseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setApproveButtonText(Messages.getString("AttachmentJDialog.attach"));
            fc.setControlButtonsAreShown(true);
            fc.setDialogTitle(Messages.getString("AttachmentJDialog.chooseAttachment"));
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int returnVal = fc.showOpenDialog(AttachmentJDialog.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                pathTextField.setText(file.toString());
            }
        }
    });
    browseButton.setEnabled(false);
    pp = new JPanel();
    pp.setLayout(new BorderLayout());
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    pp.add(p, BorderLayout.NORTH);
    p.add(pathTextField);
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.RIGHT));
    p.add(browseButton);
    pp.add(p, BorderLayout.SOUTH);
    localPanel.add(pp, BorderLayout.SOUTH);
    attachType.add(localType);
    mainPanel.add(localPanel, BorderLayout.SOUTH);

    getContentPane().add(mainPanel, BorderLayout.CENTER);

    // buttons
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.CENTER));
    JButton addButton = new JButton(Messages.getString("AttachmentJDialog.attach"));

    p.add(addButton);
    addButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            attach();
        }
    });
    JButton cancelButton = new JButton(Messages.getString("AttachmentJDialog.cancel"));
    p.add(cancelButton);
    cancelButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            AttachmentJDialog.this.dispose();
        }
    });
    getContentPane().add(p, BorderLayout.SOUTH);

    /*
     * drag and drop initialization
     */
    if (dragAndDropReference != null) {
        if (dragAndDropReference.getType() == DragAndDropReference.BROWSER_LINK) {
            urlTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(false);
            webType.setSelected(true);
            enableWebTypeButtons();
        } else {
            pathTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(true);
            webType.setSelected(false);
            enableLocalTypeButtons();
        }
        description.setText(dragAndDropReference.getTitle());
    }

    pack();
    Gfx.centerAndShowWindow(this);
}

From source file:my.grafos.Maquina.java

static void salvarGrafo() throws FileNotFoundException, IOException {
    /*// www  . j  ava2 s.co m
    FileOutputStream fos = new FileOutputStream("d:\\t.xml");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(Fabrica.listaArestas);
    oos.close();
     */
    final JFileChooser fc = new JFileChooser();
    //Handle save button action.
    int returnVal = fc.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        System.out.println("1 " + fc.getSelectedFile());
        System.out.println("2 " + file);
        //            if (Fabrica.xmlA.length() == 0) {
        if (Fabrica.xmlA.length() == 0) {
            //                System.out.println("No h dados para salvar.");
            return;
        }
        try (OutputStream output = new FileOutputStream(file.getPath())) {
            int count = 0;

            while (count < Fabrica.xmlA.length()) {
                output.write(Fabrica.xmlA.charAt(count));
                count++;
            }
            count = 0;
            while (count < Fabrica.xmlV.length()) {
                output.write(Fabrica.xmlV.charAt(count));
                count++;
            }
        } catch (IOException e) {
        }
    }

}