Example usage for javax.swing JFileChooser setFileSelectionMode

List of usage examples for javax.swing JFileChooser setFileSelectionMode

Introduction

In this page you can find the example usage for javax.swing JFileChooser setFileSelectionMode.

Prototype

@BeanProperty(preferred = true, enumerationValues = { "JFileChooser.FILES_ONLY",
        "JFileChooser.DIRECTORIES_ONLY",
        "JFileChooser.FILES_AND_DIRECTORIES" }, description = "Sets the types of files that the JFileChooser can choose.")
public void setFileSelectionMode(int mode) 

Source Link

Document

Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.

Usage

From source file:com.floreantpos.ui.model.MenuItemForm.java

protected void doSelectImageFile() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int option = fileChooser.showOpenDialog(POSUtil.getBackOfficeWindow());

    if (option == JFileChooser.APPROVE_OPTION) {
        File imageFile = fileChooser.getSelectedFile();
        try {/*  w w w.  j a va2s. c  o m*/
            byte[] itemImage = FileUtils.readFileToByteArray(imageFile);
            int imageSize = itemImage.length / 1024;

            if (imageSize > 20) {
                POSMessageDialog.showMessage(Messages.getString("MenuItemForm.0")); //$NON-NLS-1$
                itemImage = null;
                return;
            }

            ImageIcon imageIcon = new ImageIcon(
                    new ImageIcon(itemImage).getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH));
            lblImagePreview.setIcon(imageIcon);

            MenuItem menuItem = (MenuItem) getBean();
            menuItem.setImageData(itemImage);

        } catch (IOException e) {
            PosLog.error(getClass(), e);
        }
    }
}

From source file:net.lmxm.ute.gui.MainFrame.java

/**
 * Action open file.//  ww w  .j  a  v  a  2  s  .  co  m
 */
private void actionOpenFile() {
    final String prefix = "actionOpenFile() :";

    final JFileChooser fcOpen = new JFileChooser(getCurrentDirectory());

    fcOpen.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fcOpen.setFileFilter(getFileFilter());

    final int returnVal = fcOpen.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final File file = fcOpen.getSelectedFile();

        LOGGER.debug("{} opening file {}", prefix, file.getName());

        try {
            configuration = new ConfigurationReader(file).read();

            loadAndValidatePreferences(file);

            userPreferences.setLastFileEditedPath(file.getAbsolutePath());

            refreshJobsTree();
            updateTitle();
            getJobDetailsEditorScrollPane().setViewportView(null);
        } catch (final Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    } else {
        LOGGER.debug("{} cancelled by user", prefix);
    }
}

From source file:de.whiledo.iliasdownloader2.swing.service.MainController.java

protected void changeBaseDir() {
    File baseDir = new File(iliasProperties.getBaseDirectory());
    JFileChooser fileChooser = new JFileChooser(baseDir);
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(mainFrame)) {
        String s = fileChooser.getSelectedFile().getAbsolutePath();
        JOptionPane.showMessageDialog(mainFrame, "Der neue Speicherort ist jetzt " + s, "Neuer Speicherort",
                JOptionPane.INFORMATION_MESSAGE);
        iliasProperties.setBaseDirectory(s);
        saveProperties(iliasProperties);
    } else {/*from w  ww.j  av a 2s .co  m*/
        JOptionPane.showMessageDialog(mainFrame,
                "Der alte Speicherort wird beibehalten " + baseDir.getAbsolutePath(), "Speicherort",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

From source file:io.github.jeremgamer.editor.panels.components.ButtonPanel.java

public ButtonPanel(JFrame frame) {

    this.frame = frame;
    this.setSize(new Dimension(395, frame.getHeight() - 27 - 23));
    this.setLocation(300, 0);
    this.setBorder(BorderFactory.createTitledBorder("Edition du bouton"));
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    JLabel nameLabel = new JLabel("Nom : ");
    name.setPreferredSize(new Dimension(this.getWidth() - 285, 30));
    name.setEditable(false);//w w  w  .  java 2  s . c o m
    JPanel namePanel = new JPanel();
    namePanel.add(nameLabel);
    namePanel.add(name);
    JPanel textPanel = new JPanel();
    JPanel nameAndTextPanel = new JPanel();
    JLabel textLabel = new JLabel("Texte :");
    CaretListener caretUpdateText = new CaretListener() {
        public void caretUpdate(javax.swing.event.CaretEvent e) {
            JTextField text = (JTextField) e.getSource();
            bs.set("text", text.getText());
            preview.setText(text.getText());
            preview2.setText(text.getText());
        }
    };
    text.addCaretListener(caretUpdateText);
    text.setPreferredSize(new Dimension(this.getWidth() - 283, 30));
    textPanel.add(textLabel);
    textPanel.add(text);
    nameAndTextPanel.setLayout(new BoxLayout(nameAndTextPanel, BoxLayout.PAGE_AXIS));
    nameAndTextPanel.add(namePanel);
    nameAndTextPanel.add(textPanel);

    JPanel policePanel = new JPanel();
    JLabel policeLabel = new JLabel("Police : ");
    police.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            @SuppressWarnings("unchecked")
            JComboBox<String> combo = (JComboBox<String>) e.getSource();
            fontStyle = (String) combo.getSelectedItem();
            preview.setFont(new Font(fontStyle, Font.PLAIN, fontSize));
            preview2.setFont(new Font(fontStyle, Font.PLAIN, fontSize));
            bs.set("police", fontStyle);
        }

    });
    police.setPreferredSize(new Dimension(105, 30));
    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font[] fonts = e.getAllFonts();
    for (Font f : fonts) {
        police.addItem(f.getName());
    }
    police.setSelectedItem("Arial");
    policePanel.add(policeLabel);
    policePanel.add(police);

    JPanel sizePanel = new JPanel();
    size.setPreferredSize(new Dimension(60, 25));
    JLabel sizeLabel = new JLabel("Taille : ");
    sizePanel.add(sizeLabel);
    sizePanel.add(size);
    JButton colorButton = new JButton("Couleur");
    colorButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            colorFrame.setModal(false);
            JButton finish = new JButton("Terminer");
            finish.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    colorFrame.dispose();
                }

            });
            colorFrame.setLayout(new BorderLayout());
            colorFrame.add(color, BorderLayout.CENTER);
            colorFrame.add(finish, BorderLayout.SOUTH);
            colorFrame.pack();
            colorFrame.setLocation(SwingUtilities.windowForComponent(imagedButton).getX() + 325,
                    SwingUtilities.windowForComponent(imagedButton).getY() - colorFrame.getHeight() + 40);
            colorFrame.setVisible(true);
        }

    });
    sizePanel.add(colorButton);
    size.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSpinner spinner = (JSpinner) e.getSource();
            fontSize = (int) spinner.getValue();
            preview.setFont(new Font(fontStyle, Font.PLAIN, fontSize));
            preview2.setFont(new Font(fontStyle, Font.PLAIN, fontSize));
            bs.set("size", fontSize);
        }
    });

    JPanel policeAndSize = new JPanel();
    policeAndSize.setLayout(new BoxLayout(policeAndSize, BoxLayout.PAGE_AXIS));
    policeAndSize.add(policePanel);
    policeAndSize.add(sizePanel);

    JPanel top = new JPanel();
    top.add(nameAndTextPanel);
    top.add(policeAndSize);
    top.setPreferredSize(new Dimension(395, 20));

    this.add(top);

    JPanel images = new JPanel();
    images.setBorder(BorderFactory.createTitledBorder("Images"));
    images.setLayout(new GridLayout(2, 3));
    images.setPreferredSize(new Dimension(395, this.getHeight() - 320));

    JPanel imaged = new JPanel();
    imaged.setLayout(new BorderLayout());
    imaged.setBorder(BorderFactory.createTitledBorder("Icne interne"));
    imagedButton.setSelected(true);
    imagedButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent ev) {
            if (ev.getStateChange() == ItemEvent.SELECTED) {
                bs.set("strings", true);
                preview.setBorderPainted(true);
            } else if (ev.getStateChange() == ItemEvent.DESELECTED) {
                bs.set("strings", false);
                preview.setBorderPainted(false);
            }
        }
    });
    JButton browseInternal = new JButton("Parcourir");
    browseInternal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "internal.png");
                nameInternal.setText(new File(path).getName());
                nameInternal.setPreferredSize(new Dimension(imgBasic.getWidth() - 10, 30));
                preview.setIcon(new ImageIcon(path));
                preview.repaint();
                bs.set("imageInternal", new File(path).getName());
            }
        }

    });
    JPanel northImaged = new JPanel();
    northImaged.setLayout(new BorderLayout());
    northImaged.add(imagedButton, BorderLayout.NORTH);
    northImaged.add(browseInternal, BorderLayout.SOUTH);
    imaged.add(northImaged, BorderLayout.NORTH);
    imaged.add(nameInternal, BorderLayout.CENTER);
    JButton removeInternal = null;
    try {
        removeInternal = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removeInternal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/internal.png");
            file.delete();
            nameInternal.setText("");
            bs.set("imageInternal", "");
            preview.setIcon(null);
        }

    });
    imaged.add(removeInternal, BorderLayout.SOUTH);
    images.add(imaged);

    imgBasic.setBorder(BorderFactory.createTitledBorder("Base"));
    JButton browseBasic = new JButton("Parcourir");
    browseBasic.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "basic.png");
                nameBasic.setText(new File(path).getName());
                nameBasic.setPreferredSize(new Dimension(imgBasic.getWidth() - 10, 30));
                previewPanel.remove(preview);
                previewPanel.remove(preview2);
                previewPanel.add(preview2);
                color.changePreview(preview2);
                bs.set("imageBasic", new File(path).getName());
                preview2.update();
                previewPanel.repaint();
            }
        }

    });
    imgBasic.setLayout(new BorderLayout());
    imgBasic.add(browseBasic, BorderLayout.NORTH);
    imgBasic.add(nameBasic, BorderLayout.CENTER);
    JButton removeBasic = null;
    try {
        removeBasic = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removeBasic.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/basic.png");
            file.delete();
            nameBasic.setText("");
            bs.set("imageBasic", "");
            preview2.update();
            previewPanel.repaint();
            if (bs.getString("imageBasic").equals("") && bs.getString("imageEntered").equals("")
                    && bs.getString("imageExited").equals("") && bs.getString("imagePressed").equals("")
                    && bs.getString("imageReleased").equals("")) {
                previewPanel.remove(preview2);
                previewPanel.add(preview);
            }
        }

    });
    imgBasic.add(removeBasic, BorderLayout.SOUTH);
    images.add(imgBasic);

    imgEntered.setBorder(BorderFactory.createTitledBorder("Survol"));
    JButton browseEntered = new JButton("Parcourir");
    browseEntered.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "entered.png");
                nameEntered.setText(new File(path).getName());
                nameEntered.setPreferredSize(new Dimension(imgEntered.getWidth() - 10, 30));
                bs.set("imageEntered", new File(path).getName());
                preview2.update();
                previewPanel.repaint();
            }
        }

    });
    imgEntered.setLayout(new BorderLayout());
    imgEntered.add(browseEntered, BorderLayout.NORTH);
    imgEntered.add(nameEntered, BorderLayout.CENTER);
    JButton removeEntered = null;
    try {
        removeEntered = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removeEntered.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/entered.png");
            file.delete();
            nameEntered.setText("");
            bs.set("imageEntered", "");
            preview2.update();
            previewPanel.repaint();
            if (bs.getString("imageBasic").equals("") && bs.getString("imageEntered").equals("")
                    && bs.getString("imageExited").equals("") && bs.getString("imagePressed").equals("")
                    && bs.getString("imageReleased").equals("")) {
                previewPanel.remove(preview2);
                previewPanel.add(preview);
            }
        }

    });
    imgEntered.add(removeEntered, BorderLayout.SOUTH);
    images.add(imgEntered);

    imgExited.setBorder(BorderFactory.createTitledBorder("Sortie"));
    JButton browseExited = new JButton("Parcourir");
    browseExited.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "exited.png");
                nameExited.setText(new File(path).getName());
                nameExited.setPreferredSize(new Dimension(imgExited.getWidth() - 10, 30));
                bs.set("imageExited", new File(path).getName());
                preview2.update();
                previewPanel.repaint();
            }
        }

    });
    imgExited.setLayout(new BorderLayout());
    imgExited.add(browseExited, BorderLayout.NORTH);
    imgExited.add(nameExited, BorderLayout.CENTER);
    JButton removeExited = null;
    try {
        removeExited = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removeExited.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/exited.png");
            file.delete();
            nameExited.setText("");
            bs.set("imageExited", "");
            preview2.update();
            previewPanel.repaint();
            if (bs.getString("imageBasic").equals("") && bs.getString("imageEntered").equals("")
                    && bs.getString("imageExited").equals("") && bs.getString("imagePressed").equals("")
                    && bs.getString("imageReleased").equals("")) {
                previewPanel.remove(preview2);
                previewPanel.add(preview);
            }
        }

    });
    imgExited.add(removeExited, BorderLayout.SOUTH);
    images.add(imgExited);

    imgPressed.setBorder(BorderFactory.createTitledBorder("Clic"));
    JButton browsePressed = new JButton("Parcourir");
    browsePressed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "pressed.png");
                namePressed.setText(new File(path).getName());
                namePressed.setPreferredSize(new Dimension(imgPressed.getWidth() - 10, 30));
                bs.set("imagePressed", new File(path).getName());
                preview2.update();
                previewPanel.repaint();
            }
        }

    });
    imgPressed.setLayout(new BorderLayout());
    imgPressed.add(browsePressed, BorderLayout.NORTH);
    imgPressed.add(namePressed, BorderLayout.CENTER);
    JButton removePressed = null;
    try {
        removePressed = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removePressed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/pressed.png");
            file.delete();
            namePressed.setText("");
            bs.set("imagePressed", "");
            preview2.update();
            previewPanel.repaint();
            if (bs.getString("imageBasic").equals("") && bs.getString("imageEntered").equals("")
                    && bs.getString("imageExited").equals("") && bs.getString("imagePressed").equals("")
                    && bs.getString("imageReleased").equals("")) {
                previewPanel.remove(preview2);
                previewPanel.add(preview);
            }
        }

    });
    imgPressed.add(removePressed, BorderLayout.SOUTH);
    images.add(imgPressed);

    imgReleased.setBorder(BorderFactory.createTitledBorder("Relachement"));
    JButton browseReleased = new JButton("Parcourir");
    browseReleased.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "released.png");
                nameReleased.setText(new File(path).getName());
                nameReleased.setPreferredSize(new Dimension(imgReleased.getWidth() - 10, 30));
                bs.set("imageReleased", new File(path).getName());
                preview2.update();
                previewPanel.repaint();
            }
        }

    });
    imgReleased.setLayout(new BorderLayout());
    imgReleased.add(browseReleased, BorderLayout.NORTH);
    imgReleased.add(nameReleased, BorderLayout.CENTER);
    JButton removeReleased = null;
    try {
        removeReleased = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    removeReleased.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File(
                    "projects/" + Editor.getProjectName() + "/buttons/" + name.getText() + "/released.png");
            file.delete();
            nameReleased.setText("");
            bs.set("imageReleased", "");
            preview2.update();
            previewPanel.repaint();
            if (bs.getString("imageBasic").equals("") && bs.getString("imageEntered").equals("")
                    && bs.getString("imageExited").equals("") && bs.getString("imagePressed").equals("")
                    && bs.getString("imageReleased").equals("")) {
                previewPanel.remove(preview2);
                previewPanel.add(preview);
            }
        }

    });
    imgReleased.add(removeReleased, BorderLayout.SOUTH);
    images.add(imgReleased);

    this.add(images);

    JPanel action = new JPanel();
    action.setPreferredSize(new Dimension(395, -20));
    JLabel labelAction = new JLabel("Action : ");
    action.add(labelAction);
    actionList.removeAllItems();
    actionList.addItem("Aucune");
    for (String s : Actions.getActions()) {
        actionList.addItem(s);
    }
    actionList.setPreferredSize(new Dimension(this.getWidth() - 100, 30));
    actionList.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            @SuppressWarnings("unchecked")
            JComboBox<String> combo = (JComboBox<String>) event.getSource();
            bs.set("action", combo.getSelectedItem());
        }

    });
    action.add(actionList);
    this.add(action);

    JScrollPane previewScroll = new JScrollPane(previewPanel);
    previewScroll.getVerticalScrollBar().setUnitIncrement(Editor.SCROLL_SPEED);
    previewPanel.setBorder(BorderFactory.createTitledBorder("Aperu"));
    previewPanel.add(preview);
    previewScroll.setPreferredSize(new Dimension(395, 40));
    previewScroll.setBorder(null);

    this.add(previewScroll);
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private File chooseFileForSave(final String title, final File initial, final FileFilter filter) {
    final JFileChooser chooser = new JFileChooser(initial);
    chooser.addChoosableFileFilter(filter);
    chooser.setAcceptAllFileFilterUsed(true);
    chooser.setMultiSelectionEnabled(false);
    chooser.setDialogTitle(title);/* w  ww . j a  v  a  2s . c o  m*/
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    final File result;
    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        result = chooser.getSelectedFile();
    } else {
        result = null;
    }
    return result;
}

From source file:net.pms.newgui.NavigationShareTab.java

private PanelBuilder initSharedFoldersGuiComponents(CellConstraints cc) {
    // Apply the orientation for the locale
    ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale());
    String colSpec = FormLayoutUtil.getColSpec(SHARED_FOLDER_COL_SPEC, orientation);

    FormLayout layoutFolders = new FormLayout(colSpec, SHARED_FOLDER_ROW_SPEC);
    PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
    builderFolder.opaque(true);/*from   w ww  .j a v a2  s . co  m*/

    JComponent cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"),
            FormLayoutUtil.flip(cc.xyw(1, 1, 7), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    folderTableModel = new SharedFoldersTableModel();
    sharedFolders = new JTable(folderTableModel);

    JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem menuItemMarkPlayed = new JMenuItem(Messages.getString("FoldTab.75"));
    JMenuItem menuItemMarkUnplayed = new JMenuItem(Messages.getString("FoldTab.76"));

    menuItemMarkPlayed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0);
            TableFilesStatus.setDirectoryFullyPlayed(path, true);
        }
    });

    menuItemMarkUnplayed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0);
            TableFilesStatus.setDirectoryFullyPlayed(path, false);
        }
    });

    popupMenu.add(menuItemMarkPlayed);
    popupMenu.add(menuItemMarkUnplayed);

    sharedFolders.setComponentPopupMenu(popupMenu);

    /* An attempt to set the correct row height adjusted for font scaling.
     * It sets all rows based on the font size of cell (0, 0). The + 4 is
     * to allow 2 pixels above and below the text. */
    DefaultTableCellRenderer cellRenderer = (DefaultTableCellRenderer) sharedFolders.getCellRenderer(0, 0);
    FontMetrics metrics = cellRenderer.getFontMetrics(cellRenderer.getFont());
    sharedFolders.setRowHeight(metrics.getLeading() + metrics.getMaxAscent() + metrics.getMaxDescent() + 4);
    sharedFolders.setIntercellSpacing(new Dimension(8, 2));

    final JPanel tmpsharedPanel = sharedPanel;

    addButton.setToolTipText(Messages.getString("FoldTab.9"));
    addButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser;
            try {
                chooser = new JFileChooser();
            } catch (Exception ee) {
                chooser = new JFileChooser(new RestrictedFileSystemView());
            }
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog((Component) e.getSource());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                int firstSelectedRow = sharedFolders.getSelectedRow();
                if (firstSelectedRow >= 0) {
                    ((SharedFoldersTableModel) sharedFolders.getModel()).insertRow(firstSelectedRow,
                            new Object[] { chooser.getSelectedFile().getAbsolutePath(), true });
                } else {
                    ((SharedFoldersTableModel) sharedFolders.getModel())
                            .addRow(new Object[] { chooser.getSelectedFile().getAbsolutePath(), true });
                }
            }
        }
    });
    builderFolder.add(addButton, FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation));

    removeButton.setToolTipText(Messages.getString("FoldTab.36"));
    removeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = sharedFolders.getSelectedRows();
            if (rows.length > 0) {
                if (rows.length > 1) {
                    if (JOptionPane.showConfirmDialog(tmpsharedPanel,
                            String.format(Messages.getString("SharedFolders.ConfirmRemove"), rows.length),
                            Messages.getString("Dialog.Confirm"), JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
                        return;
                    }
                }
                for (int i = rows.length - 1; i >= 0; i--) {
                    PMS.get().getDatabase().removeMediaEntriesInFolder(
                            (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0));
                    ((SharedFoldersTableModel) sharedFolders.getModel()).removeRow(rows[i]);
                }
            }
        }
    });
    builderFolder.add(removeButton, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));

    arrowDownButton.setToolTipText(Messages.getString("SharedFolders.ArrowDown"));
    arrowDownButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < sharedFolders.getRowCount() - 1; i++) {
                if (sharedFolders.isRowSelected(i)) {
                    Object value1 = sharedFolders.getValueAt(i, 0);
                    boolean value2 = (boolean) sharedFolders.getValueAt(i, 1);

                    sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 0), i, 0);
                    sharedFolders.setValueAt(value1, i + 1, 0);
                    sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 1), i, 1);
                    sharedFolders.setValueAt(value2, i + 1, 1);
                    sharedFolders.changeSelection(i + 1, 1, false, false);

                    break;
                }
            }
        }
    });
    builderFolder.add(arrowDownButton, FormLayoutUtil.flip(cc.xy(4, 3), colSpec, orientation));

    arrowUpButton.setToolTipText(Messages.getString("SharedFolders.ArrowUp"));
    arrowUpButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 1; i < sharedFolders.getRowCount(); i++) {
                if (sharedFolders.isRowSelected(i)) {
                    Object value1 = sharedFolders.getValueAt(i, 0);
                    boolean value2 = (boolean) sharedFolders.getValueAt(i, 1);

                    sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 0), i, 0);
                    sharedFolders.setValueAt(value1, i - 1, 0);
                    sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 1), i, 1);
                    sharedFolders.setValueAt(value2, i - 1, 1);
                    sharedFolders.changeSelection(i - 1, 1, false, false);

                    break;

                }
            }
        }
    });
    builderFolder.add(arrowUpButton, FormLayoutUtil.flip(cc.xy(5, 3), colSpec, orientation));

    scanButton.setToolTipText(Messages.getString("FoldTab.2"));
    scanBusyIcon.start();
    scanBusyDisabledIcon.start();
    scanButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (configuration.getUseCache()) {
                DLNAMediaDatabase database = PMS.get().getDatabase();

                if (database != null) {
                    if (database.isScanLibraryRunning()) {
                        int option = JOptionPane.showConfirmDialog(looksFrame, Messages.getString("FoldTab.10"),
                                Messages.getString("Dialog.Question"), JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            database.stopScanLibrary();
                            looksFrame.setStatusLine(Messages.getString("FoldTab.41"));
                            scanButton.setEnabled(false);
                            scanButton.setToolTipText(Messages.getString("FoldTab.41"));
                        }
                    } else {
                        database.scanLibrary();
                        scanButton.setIcon(scanBusyIcon);
                        scanButton.setRolloverIcon(scanBusyRolloverIcon);
                        scanButton.setPressedIcon(scanBusyPressedIcon);
                        scanButton.setDisabledIcon(scanBusyDisabledIcon);
                        scanButton.setToolTipText(Messages.getString("FoldTab.40"));
                    }
                }
            }
        }
    });

    /*
     * Hide the scan button in basic mode since it's better to let it be done in
     * realtime.
     */
    if (!configuration.isHideAdvancedOptions()) {
        builderFolder.add(scanButton, FormLayoutUtil.flip(cc.xy(6, 3), colSpec, orientation));
    }

    scanButton.setEnabled(configuration.getUseCache());

    isScanSharedFoldersOnStartup = new JCheckBox(Messages.getString("NetworkTab.StartupScan"),
            configuration.isScanSharedFoldersOnStartup());
    isScanSharedFoldersOnStartup.setToolTipText(Messages.getString("NetworkTab.StartupScanTooltip"));
    isScanSharedFoldersOnStartup.setContentAreaFilled(false);
    isScanSharedFoldersOnStartup.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            configuration.setScanSharedFoldersOnStartup((e.getStateChange() == ItemEvent.SELECTED));
        }
    });

    builderFolder.add(isScanSharedFoldersOnStartup, FormLayoutUtil.flip(cc.xy(7, 3), colSpec, orientation));

    updateSharedFolders();

    JScrollPane pane = new JScrollPane(sharedFolders);
    Dimension d = sharedFolders.getPreferredSize();
    pane.setPreferredSize(new Dimension(d.width, sharedFolders.getRowHeight() * 2));
    builderFolder.add(pane, FormLayoutUtil.flip(cc.xyw(1, 5, 7, CellConstraints.DEFAULT, CellConstraints.FILL),
            colSpec, orientation));

    return builderFolder;
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private File chooseFileForOpen(final String title, final File initial,
        final AtomicReference<FileFilter> selectedFilter, final FileFilter... filter) {
    final JFileChooser chooser = new JFileChooser(initial);
    for (final FileFilter f : filter) {
        chooser.addChoosableFileFilter(f);
    }//  www .jav a2  s.co m
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setMultiSelectionEnabled(false);
    chooser.setDialogTitle(title);
    chooser.setFileFilter(filter[0]);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    final File result;
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        result = chooser.getSelectedFile();
        if (selectedFilter != null) {
            selectedFilter.set(chooser.getFileFilter());
        }
    } else {
        result = null;
    }
    return result;
}

From source file:de.codesourcery.jasm16.ide.ui.views.WorkspaceExplorer.java

protected JPopupMenu createPopupMenu(final WorkspaceTreeNode selectedNode) {
    final JPopupMenu popup = new JPopupMenu();

    int openProjects = 0;
    int closedProjects = 0;
    for (IAssemblyProject p : workspace.getAllProjects()) {
        if (p.isOpen()) {
            openProjects++;/*from  w w  w  .  j ava 2s .c  om*/
        } else {
            closedProjects++;
        }
    }

    // open debugger
    final IAssemblyProject project = getProject(selectedNode);
    if (project != null) {
        if (project.isOpen()) {
            addMenuEntry(popup, "Close project", new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    workspace.closeProject(project);
                }
            });
        } else {
            addMenuEntry(popup, "Open project", new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    workspace.openProject(project);
                }
            });
        }

        addMenuEntry(popup, "Build project", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    project.getProjectBuilder().build();
                } catch (Exception ex) {
                    LOG.error("Failed to build " + project, ex);
                    UIUtils.showErrorDialog(null, "Building project '" + project.getName() + "' failed",
                            "Building the project failed: " + ex.getMessage(), ex);
                }
            }
        });

        if (project.getProjectBuilder() == null) {
            throw new RuntimeException("Internal error, project " + project.getName() + " has no builder ??");
        }
        final IResource executable = project.getProjectBuilder().getExecutable();
        if (executable != null) {
            addMenuEntry(popup, "Open in debugger", new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        openDebugPerspective(project, executable, perspectivesManager);
                    } catch (IOException e1) {
                        LOG.error(
                                "Failed to open debug perspective for " + project + " , resource " + executable,
                                e1);
                    }
                }
            });
        }
    }

    if (canCreateFileIn(selectedNode)) {
        addMenuEntry(popup, "New source file...", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    createNewSourceFile(selectedNode);
                } catch (IOException e1) {
                    LOG.error("actionPerformed(): ", e1);
                }
            }
        });
    }

    addMenuEntry(popup, "New project...", new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                createNewProject();
            } catch (Exception e1) {
                LOG.error("actionPerformed(): ", e1);
                UIUtils.showErrorDialog(panel, "Failed to create project",
                        "Project creation failed: " + e1.getMessage());
            }
        }
    });

    if (selectedNode != null) {
        addMenuEntry(popup, "Delete...", new ActionListener() {

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

        });
    }

    addMenuEntry(popup, "Refresh", new ActionListener() {

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

    addMenuEntry(popup, "Import existing project...", new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser fc = new JFileChooser(workspace.getBaseDirectory());
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            final int returnVal = fc.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                final File directory = fc.getSelectedFile();
                try {
                    workspace.importProject(directory);
                } catch (Exception e1) {
                    UIUtils.showErrorDialog(null, "Failed to import project",
                            "Error while importing project: " + e1.getMessage());
                }
            }
        }

    });

    if (project != null) {
        addMenuEntry(popup, "Project properties...", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ProjectConfigurationView view = (ProjectConfigurationView) getViewContainer()
                        .getViewByID(ProjectConfigurationView.ID);
                if (view == null) {
                    view = new ProjectConfigurationView() {

                        @Override
                        protected void onSave() {
                            apply(project.getConfiguration());

                            try {
                                project.getConfiguration().save();
                            } catch (IOException e) {
                                UIUtils.showErrorDialog(null, "Error", "Failed to save project options", e);
                            } finally {
                                getViewContainer().disposeView(this);
                            }
                        }

                        @Override
                        protected void onCancel() {
                            getViewContainer().disposeView(this);
                        }
                    };
                    getViewContainer().addView(view);
                }

                view.setProject(project);
                view.getViewContainer().toFront(view);
            }

        });
    }

    if (closedProjects > 0) {
        addMenuEntry(popup, "Open ALL projects", new ActionListener() {

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

    if (openProjects > 0) {
        addMenuEntry(popup, "Close ALL projects", new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                closeAllProjects();
            }
        });
    }
    return popup;
}

From source file:org.fhaes.fhsamplesize.view.FHSampleSize.java

/**
 * Show open file dialog so the user may choose a file to edit.
 * /*from  w ww  .ja  v a2s.  c om*/
 * @return the chosen file if okay was pressed, null if cancel was pressed
 */
private File loadFromOpenFileDialog() {

    String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_READ_FOLDER, null);
    JFileChooser fc;

    if (lastVisitedFolder != null)
        fc = new JFileChooser(lastVisitedFolder);
    else
        fc = new JFileChooser();

    fc.setDialogTitle("Select a FHX2 file for sample size analysis");
    fc.setFileFilter(new FHXFileFilter());
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(true);

    int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        App.prefs.setPref(PrefKey.PREF_LAST_READ_FOLDER, fc.getSelectedFile().getPath());
        return fc.getSelectedFile();
    }
    return null;
}

From source file:org.biojava.bio.view.MotifAnalyzer.java

public void runMethod(MotifFinder method) {
    final JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new Filter("fasta"));
    fc.setDialogTitle("Select Sequence File (in FASTA format)");
    int returnVal = JFileChooser.CANCEL_OPTION;
    if (datasetComboBox.getSelectedItem().equals(Dataset.unknown))
        returnVal = fc.showOpenDialog(MotifAnalyzer.this.mainFrame);

    if (!datasetComboBox.getSelectedItem().equals(Dataset.unknown)
            || (returnVal == JFileChooser.APPROVE_OPTION)) {
        try {//from  ww w . jav a 2  s  . co m
            final JFileChooser readDirectory = new JFileChooser();
            readDirectory.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (readDirectory.showOpenDialog(MotifAnalyzer.this.mainFrame) == JFileChooser.APPROVE_OPTION) {
                Dataset dataset = (Dataset) datasetComboBox.getSelectedItem();
                int type = datasetTypeComboBox.getSelectedIndex();
                String fileName = (returnVal == JFileChooser.APPROVE_OPTION)
                        ? fc.getSelectedFile().getCanonicalPath()
                        : TompaDataset.getDatasetSequenceFileName(dataset);
                int i = Integer.parseInt(numOfMotifs.getText());
                int w = Integer.parseInt(motifWidth.getText());
                int t = Integer.parseInt(numOfTrials.getText());
                OrganismCode organism = OrganismCode.getOrganism(organismType.getSelectedIndex());
                log.info("Runninf method: " + method.name());
                log.info("FileName: " + fileName);
                log.info("Outputfile: " + readDirectory.getSelectedFile().getCanonicalPath());
                log.info("Dataset: " + dataset.name());
                log.info("DatasetType: " + type);
                controller.runAndEvaluate(method, fileName, i, w, t, organism, dataset,
                        readDirectory.getSelectedFile().getCanonicalPath());
                displayCharts();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(mainFrame, "An Error occured", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}