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:modelibra.swing.app.util.FileSelector.java

/**
 * Gets the saved file given a file path.
 * /*  www  . j  a v a 2s.  c  o  m*/
 * @param path
 *            path
 * @param lang
 *            language
 * @return file
 */
public File getSaveFile(String path, NatLang lang) {
    File selectedFile = null;
    File currentFile = null;
    if (path != null && !path.equalsIgnoreCase("?")) {
        currentFile = new File(path);
    } else
        currentFile = lastSavedFile;

    JFileChooser chooser = new JFileChooser();
    chooser.setLocale(lang.getLocale());
    if (currentFile != null) {
        chooser.setCurrentDirectory(currentFile);
    }
    int returnVal = chooser.showSaveDialog(chooser);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile(); // a complete path
        if (selectedFile.exists()) {
            if (!replaceFile(null, lang)) {
                selectedFile = null;
            }
        }
    }
    lastSavedFile = selectedFile;

    return selectedFile;
}

From source file:DragFileDemo.java

public DragFileDemo() {
    super(new BorderLayout());

    fc = new JFileChooser();
    ;//from   w  ww.  jav a 2s  .co  m
    fc.setMultiSelectionEnabled(true);
    fc.setDragEnabled(true);
    fc.setControlButtonsAreShown(false);
    JPanel fcPanel = new JPanel(new BorderLayout());
    fcPanel.add(fc, BorderLayout.CENTER);

    clear = new JButton("Clear All");
    clear.addActionListener(this);
    JPanel buttonPanel = new JPanel(new BorderLayout());
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    buttonPanel.add(clear, BorderLayout.LINE_END);

    JPanel upperPanel = new JPanel(new BorderLayout());
    upperPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    upperPanel.add(fcPanel, BorderLayout.CENTER);
    upperPanel.add(buttonPanel, BorderLayout.PAGE_END);

    //The TabbedPaneController manages the panel that
    //contains the tabbed pane. When there are no files
    //the panel contains a plain text area. Then, as
    //files are dropped onto the area, the tabbed panel
    //replaces the file area.
    JTabbedPane tabbedPane = new JTabbedPane();
    JPanel tabPanel = new JPanel(new BorderLayout());
    tabPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    tpc = new TabbedPaneController(tabbedPane, tabPanel);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel, tabPanel);
    splitPane.setDividerLocation(400);
    splitPane.setPreferredSize(new Dimension(530, 650));
    add(splitPane, BorderLayout.CENTER);
}

From source file:com.stam.batchmove.BatchMoveUtils.java

public static void showFilesFrame(Object[][] data, String[] columnNames, final JFrame callerFrame) {
    final FilesFrame filesFrame = new FilesFrame();

    DefaultTableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override/*from www  .j a va2s.c o  m*/
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 0;
        }
    };
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(JLabel.CENTER);
    final JTable table = new JTable(model);
    for (int i = 1; i < table.getColumnCount(); i++) {
        table.setDefaultRenderer(table.getColumnClass(i), renderer);
    }
    //            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setRowHeight(30);
    table.getTableHeader().setFont(new Font("Serif", Font.BOLD, 14));
    table.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    table.setRowSelectionAllowed(false);
    table.getColumnModel().getColumn(0).setMaxWidth(35);
    table.getColumnModel().getColumn(1).setPreferredWidth(350);
    table.getColumnModel().getColumn(2).setPreferredWidth(90);
    table.getColumnModel().getColumn(2).setMaxWidth(140);
    table.getColumnModel().getColumn(3).setMaxWidth(90);

    JPanel tblPanel = new JPanel();
    JPanel btnPanel = new JPanel();

    tblPanel.setLayout(new BorderLayout());
    if (table.getRowCount() > 15) {
        JScrollPane scrollPane = new JScrollPane(table);
        tblPanel.add(scrollPane, BorderLayout.CENTER);
    } else {
        tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tblPanel.add(table, BorderLayout.CENTER);
    }

    btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    filesFrame.setMinimumSize(new Dimension(800, 600));
    filesFrame.setLayout(new BorderLayout());
    filesFrame.add(tblPanel, BorderLayout.NORTH);
    filesFrame.add(btnPanel, BorderLayout.SOUTH);

    final JLabel resultsLabel = new JLabel();

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filesFrame.setVisible(false);
            callerFrame.setVisible(true);
        }
    });

    JButton moveBtn = new JButton("Copy");
    moveBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setDialogTitle("Choose target directory");
            int selVal = fileChooser.showOpenDialog(null);
            if (selVal == JFileChooser.APPROVE_OPTION) {
                File selection = fileChooser.getSelectedFile();
                String targetPath = selection.getAbsolutePath();

                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                int nRow = dtm.getRowCount();
                int copied = 0;
                for (int i = 0; i < nRow; i++) {
                    Boolean selected = (Boolean) dtm.getValueAt(i, 0);
                    String filePath = dtm.getValueAt(i, 1).toString();

                    if (selected) {
                        try {
                            FileUtils.copyFileToDirectory(new File(filePath), new File(targetPath));
                            dtm.setValueAt("Copied", i, 3);
                            copied++;
                        } catch (Exception ex) {
                            Logger.getLogger(SelectionFrame.class.getName()).log(Level.SEVERE, null, ex);
                            dtm.setValueAt("Failed", i, 3);
                        }
                    }
                }
                resultsLabel.setText(copied + " files copied. Finished!");
            }
        }
    });
    btnPanel.add(cancelBtn);
    btnPanel.add(moveBtn);
    btnPanel.add(resultsLabel);

    filesFrame.revalidate();
    filesFrame.setVisible(true);

    callerFrame.setVisible(false);
}

From source file:table.FrequencyTablePanel.java

public String doSaveAs(File f) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Files", "pdf");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);/*w w  w  .  jav  a2s  .  c o m*/
    String filename = "";
    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        filename = fileChooser.getSelectedFile().getPath();
        if (!filename.endsWith(".png")) {
            filename = filename + ".png";
        }
        saveTableAsPNG(new File(filename), this.table, getWidth(), getHeight());
    }
    return filename;
}

From source file:de.peterspan.csv2db.ui.FileSelectionPanel.java

private JFileChooser getFileChooser() {
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fc.setAcceptAllFileFilterUsed(false);

    fc.addChoosableFileFilter(new FileFilter() {

        @Override//from ww  w. j  a v  a  2s  .  c  o  m
        public String getDescription() {
            return "CSV Files";
        }

        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            }

            return FilenameUtils.isExtension(file.getName().toLowerCase(), "csv");
        }
    });

    return fc;
}

From source file:de.fionera.javamailer.gui.mainView.controllerMain.java

/**
 * Adds the Actionlisteners to the Mainview
 *
 * @param viewMain The Mainview//  w  w w. j a  va2  s.c  o  m
 */
private void addActionListener(viewMain viewMain) {
    /**
     * Changes the Amount in the AmountLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderAmountMails().addChangeListener(e -> {
        Main.amountMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberAmountMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Changes the Delay in the DelayLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderDelayMails().addChangeListener(e -> {
        Main.delayMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberDelayMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Closes the Program, when close is clicked
     */
    viewMain.getCloseItem().addActionListener(e -> System.exit(0));

    /**
     * Opens the Settings when the settingsbutton is clicked
     */
    viewMain.getSettingsItem().addActionListener(e -> new controllerSettings());

    /**
     * Save current Setup
     */
    viewMain.getSaveSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();
        JFrame parentFrame = new JFrame();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");

        int userSelection = jChooser.showSaveDialog(parentFrame);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = new File(jChooser.getSelectedFile() + ".jms");

            saveSetup(viewMain, fileToSave, new ObjectMapper());
        }
    });

    /**
     * Load Setup
     */
    viewMain.getLoadSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");
        jChooser.showOpenDialog(null);

        File file = jChooser.getSelectedFile();

        if (file != null) {
            if (file.getName().endsWith("jms")) {
                try {
                    loadSetup(viewMain, file, new ObjectMapper());
                } catch (Exception error) {
                    error.printStackTrace();
                }
            }
        }
    });

    /**
     * Opens the Open File dialog and start the Parsing of it
     */
    viewMain.getSelectRecipientsPanel().getSelectExcelFileButton().addActionListener(e -> {
        DefaultTableModel model;
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel 97 - 2003 (.xls)", "xls"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel (.xlsx)", "xlsx"));
        jChooser.setDialogTitle("Select only Excel workbooks");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("xls")) {
                ArrayList returnedData = parseFilesForImport.parseXLSFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else if (file.getName().endsWith("xlsx")) {
                ArrayList returnedData = parseFilesForImport.parseXLSXFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else {
                JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",
                        JOptionPane.ERROR_MESSAGE);

                model = new DefaultTableModel();
            }
        } else {
            model = new DefaultTableModel();

        }

        viewMain.getSelectRecipientsPanel().getTable().setModel(model);

        int tableWidth = model.getColumnCount() * 150;
        int tableHeight = model.getRowCount() * 25;
        viewMain.getSelectRecipientsPanel().getTable().setPreferredSize(new Dimension(tableWidth, tableHeight));
        viewMain.getCheckAllSettings().getLabelRecipientsAmount().setText("" + model.getRowCount());
        viewMain.getCheckAllSettings().getLabelTimeAmount()
                .setText(""
                        + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                        + " Seconds");
    });

    /**
     * Starts the sending of th Mails, when the send button is clicked
     */
    viewMain.getCheckAllSettings().getSendMails().addActionListener(e -> {

        String subject = viewMain.getSetMailSettingsPanel().getFieldSubject().getText();
        Sender sender = (Sender) viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem();
        JTable table = viewMain.getSelectRecipientsPanel().getTable();

        if (table != null && sender != null && !subject.equals("")) {
            new sendMails(viewMain);
        }
    });

    /**
     * Clears the Table on buttonclick
     */
    viewMain.getSelectRecipientsPanel().getClearTableButton().addActionListener(e -> {
        viewMain.getSelectRecipientsPanel().getTable().setModel(new DefaultTableModel());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * Removes a single Row on menu click in the editMailPanel
     */
    viewMain.getSelectRecipientsPanel().getDeleteRow().addActionListener(e -> {
        ((DefaultTableModel) viewMain.getSelectRecipientsPanel().getTable().getModel())
                .removeRow(viewMain.getSelectRecipientsPanel().getTable().getSelectedRowCount());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * The Changes the displayed Value when the Time in the Timespinner is getting changed.
     */
    viewMain.getSetMailSettingsPanel().getTimeSpinner().addChangeListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());

    });
    viewMain.getSetMailSettingsPanel().getDatePicker().addActionListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());
    });

    /**
     * Actionevent for the Edit Sender Button
     */
    viewMain.getSetMailSettingsPanel().getButtonEditSender()
            .addActionListener(e -> new controllerEditSender(controllerMain));

    /**
     * Actionevent for the Import Button in the EditMail View
     */
    viewMain.getEditMailPanel().getImportWord().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Word 97 - 2003 (.doc)", "doc"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("HTML File (.html)", "html"));
        jChooser.setDialogTitle("Select only Word Documents");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("doc")) {
                String returnedData = parseFilesForImport.parseDOCFile(file);
                viewMain.getEditMailPanel().setEditorText(returnedData);

            } else if (file.getName().endsWith("html")) {
                String content = "";
                try {
                    content = Jsoup.parse(file, "UTF-8").toString();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                viewMain.getEditMailPanel().setEditorText(content);

            } else {
                JOptionPane.showMessageDialog(null, "Please select a Document file.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    /**
     * The Tab Changelistener
     * The first if Statement sets the Labels on the Checkallsettings Panel to the right Values
     */
    viewMain.getTabbedPane().addChangeListener(e -> {
        if (viewMain.getTabbedPane().getSelectedComponent() == viewMain.getCheckAllSettings()) {

            viewMain.getCheckAllSettings().getLabelMailBelow()
                    .setText(viewMain.getEditMailPanel().getEditorText()); //Displays the Mail

            viewMain.getCheckAllSettings().getLabelRecipientsAmount()
                    .setText("" + viewMain.getSelectRecipientsPanel().getTable().getModel().getRowCount()); //Displays the Amount of Recipients

            if (viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem() != null) {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText(
                        viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem().toString());
            } else {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText("Select a Sender first");
            }

            viewMain.getCheckAllSettings().getLabelSubjectInserted()
                    .setText(viewMain.getSetMailSettingsPanel().getFieldSubject().getText()); //Displays the Subject

            if (viewMain.getSetMailSettingsPanel().getCheckBoxDelayMails().isSelected()) {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(true);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(true);

                viewMain.getCheckAllSettings().getLabelDelayNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()); //The Delay Number
                viewMain.getCheckAllSettings().getLabelAmountNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()); //The Amount of Mail in one package
                viewMain.getCheckAllSettings().getLabelTimeAmount()
                        .setText(""
                                + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                        * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                        / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                                + " Seconds"); //The Time the Sending needs

            } else {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(false);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(false);
            }

            if (viewMain.getSetMailSettingsPanel().getCheckBoxSendLater().isSelected()) {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingAt()
                        .setText(viewMain.getSetMailSettingsPanel().getDate().toString());

            } else {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(false);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(false);
            }

        }
    });

}

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

private JFileChooser prepareFileChooser() {
    JFileChooser ofd = new JFileChooser();
    ofd.setFileSelectionMode(JFileChooser.FILES_ONLY);
    ofd.setMultiSelectionEnabled(false);
    ofd.setDialogTitle(Messages.get(dialogTitleCode));
    ofd.setApproveButtonText(Messages.get(approvalButtonTextCode));
    onFileChooserPostConstrct(ofd);// w  ww  .  j a v  a  2s  .  c o m
    suggestTarget(ofd);
    return ofd;
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private File loadFileChooser(boolean dir, FileFilter filter, String text) {
    File result = null;// ww w. ja  va 2 s  . co m
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    disableNewFolderButton(fc);
    if (text != null) {
        fc.setSelectedFile(new File(text));
    }
    if (dir) {
        fc.setDialogTitle("");
        File lastDir = new File(
                Preferences.userRoot().get("lastDir", fc.getCurrentDirectory().getAbsolutePath()));
        fc.setCurrentDirectory(lastDir);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            jTextField1.setText(result.getAbsolutePath());
            Preferences.userRoot().put("lastDir", result.getParentFile().getAbsolutePath());
        }
    } else {
        File lastSaved = null;
        File lastSelected = null;
        if (filter != null) {
            fc.setDialogTitle("Save As...");
            lastSaved = new File(
                    Preferences.userRoot().get("lastSaved", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSaved);
            fc.setFileFilter(filter);
        } else {
            fc.setDialogTitle("");
            lastSelected = new File(
                    Preferences.userRoot().get("lastSelected", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSelected);
            fc.setAcceptAllFileFilterUsed(true);
        }
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            if (lastSaved != null) {
                Preferences.userRoot().put("lastSaved", result.getParentFile().getAbsolutePath());
            }
            if (lastSelected != null) {
                Preferences.userRoot().put("lastSelected", result.getParentFile().getAbsolutePath());
            }
        }
    }
    return result;
}

From source file:fll.scheduler.ChooseChallengeDescriptor.java

private void initComponents() {
    getContentPane().setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.weightx = 1;/*w w w .  ja  v a  2  s. c o m*/
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.BOTH;
    final JTextArea instructions = new JTextArea(
            "Choose a challenge description from the drop down list OR choose a file containing your custom challenge description.",
            3, 40);
    instructions.setEditable(false);
    instructions.setWrapStyleWord(true);
    instructions.setLineWrap(true);
    getContentPane().add(instructions, gbc);

    gbc = new GridBagConstraints();
    mCombo = new JComboBox<DescriptionInfo>();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    getContentPane().add(mCombo, gbc);
    mCombo.setRenderer(new DescriptionInfoRenderer());
    mCombo.setEditable(false);
    final List<DescriptionInfo> descriptions = DescriptionInfo.getAllKnownChallengeDescriptionInfo();
    for (final DescriptionInfo info : descriptions) {
        mCombo.addItem(info);
    }

    mFileField = new JLabel();
    gbc = new GridBagConstraints();
    gbc.weightx = 1;
    getContentPane().add(mFileField, gbc);

    final JButton chooseButton = new JButton("Choose File");
    gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    getContentPane().add(chooseButton, gbc);
    chooseButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ae) {
            mFileField.setText(null);

            final JFileChooser fileChooser = new JFileChooser();
            final FileFilter filter = new BasicFileFilter("FLL Description (xml)", new String[] { "xml" });
            fileChooser.setFileFilter(filter);

            final int returnVal = fileChooser.showOpenDialog(ChooseChallengeDescriptor.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                final File selectedFile = fileChooser.getSelectedFile();
                mFileField.setText(selectedFile.getAbsolutePath());
            }
        }
    });

    final Box buttonPanel = new Box(BoxLayout.X_AXIS);
    gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    getContentPane().add(buttonPanel, gbc);

    buttonPanel.add(Box.createHorizontalGlue());
    final JButton ok = new JButton("Ok");
    buttonPanel.add(ok);
    ok.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ae) {

            // use the selected description if nothing is entered in the file box
            final DescriptionInfo descriptionInfo = mCombo.getItemAt(mCombo.getSelectedIndex());
            if (null != descriptionInfo) {
                mSelected = descriptionInfo.getURL();
            }

            final String text = mFileField.getText();
            if (!StringUtils.isEmpty(text)) {
                final File file = new File(text);
                if (file.exists()) {
                    try {
                        mSelected = file.toURI().toURL();
                    } catch (final MalformedURLException e) {
                        throw new FLLInternalException("Can't turn file into URL?", e);
                    }
                }
            }

            setVisible(false);
        }
    });

    final JButton cancel = new JButton("Cancel");
    buttonPanel.add(cancel);
    cancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ae) {
            mSelected = null;
            setVisible(false);
        }
    });

    pack();
}

From source file:ImageIOTest.java

/**
 * Open a file and load the images.// ww  w. j  a va  2s. c o m
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}