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:components.FileChooserDemo2.java

public void actionPerformed(ActionEvent e) {
    //Set up the file chooser.
    if (fc == null) {
        fc = new JFileChooser();

        //Add a custom file filter and disable the default
        //(Accept All) file filter.
        fc.addChoosableFileFilter(new ImageFilter());
        fc.setAcceptAllFileFilterUsed(false);

        //Add custom icons for file types.
        fc.setFileView(new ImageFileView());

        //Add the preview pane.
        fc.setAccessory(new ImagePreview(fc));
    }/* w w  w .  ja  v  a 2s.  co  m*/

    //Show it.
    int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");

    //Process the results.
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        log.append("Attaching file: " + file.getName() + "." + newline);
    } else {
        log.append("Attachment cancelled by user." + newline);
    }
    log.setCaretPosition(log.getDocument().getLength());

    //Reset the file chooser for the next time it's shown.
    fc.setSelectedFile(null);
}

From source file:SwingFileChooserDemo.java

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

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);//from  ww w .ja va  2 s.  c  o m
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    //Uncomment one of the following lines to try a different
    //file selection mode. The first allows just directories
    //to be selected (and, at least in the Java look and feel,
    //shown). The second allows both files and directories
    //to be selected. If you leave these lines commented out,
    //then the default mode (FILES_ONLY) will be used.
    //
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    //Create the open button. We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    openButton = new JButton("Open a File...", createImageIcon("images/Open16.gif"));
    openButton.addActionListener(this);

    //Create the save button. We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...", createImageIcon("images/Save16.gif"));
    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

From source file:calendarexportplugin.exporter.CalExporter.java

/**
 * Shows a file chooser for calendar Files.
 *
 * @return selected File/* ww  w.ja va 2  s .c om*/
 * @param programs
 *          programs that are exported
 */
private File chooseFile(Program[] programs) {
    JFileChooser select = new JFileChooser();

    ExtensionFileFilter vCal = new ExtensionFileFilter(mExtension, mExtensionFilter);
    select.addChoosableFileFilter(vCal);
    String ext = "." + mExtension;

    if (mSavePath != null) {
        select.setSelectedFile(new File(mSavePath));
        select.setFileFilter(vCal);
    }

    // check if all programs have same title. if so, use as filename
    String fileName = programs[0].getTitle();
    for (int i = 1; i < programs.length; i++) {
        if (!programs[i].getTitle().equals(fileName)) {
            fileName = "";
        }
    }

    fileName = CalendarToolbox.cleanFilename(fileName);

    if (StringUtils.isNotEmpty(fileName)) {
        if (mSavePath == null) {
            mSavePath = "";
        }
        select.setSelectedFile(new File((new File(mSavePath).getParent()) + File.separator + fileName + ext));
    }

    if (select.showSaveDialog(
            CalendarExportPlugin.getInstance().getBestParentFrame()) == JFileChooser.APPROVE_OPTION) {

        String filename = select.getSelectedFile().getAbsolutePath();

        if (!filename.toLowerCase().endsWith(ext)) {
            if (filename.endsWith(".")) {
                filename = filename.substring(0, filename.length() - 1);
            }
            filename = filename + ext;
        }

        return new File(filename);
    }

    return null;
}

From source file:test.integ.be.fedict.performance.util.PerformanceResultDialog.java

public PerformanceResultDialog(PerformanceResultsData data) {

    super((Frame) null, "Performance test results");
    setSize(1000, 800);//from w w  w  . j  a v a2s  . co m

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    JMenuItem savePerformanceMenuItem = new JMenuItem("Save Performance");
    fileMenu.add(savePerformanceMenuItem);
    savePerformanceMenuItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save as PNG...");
            int result = fileChooser.showSaveDialog(PerformanceResultDialog.this);
            if (JFileChooser.APPROVE_OPTION == result) {
                File file = fileChooser.getSelectedFile();
                try {
                    ChartUtilities.saveChartAsPNG(file, performanceChart, 1024, 768);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "error saving to file: " + e.getMessage());
                }
            }
        }

    });
    JMenuItem saveMemoryMenuItem = new JMenuItem("Save Memory");
    fileMenu.add(saveMemoryMenuItem);
    saveMemoryMenuItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save as PNG...");
            int result = fileChooser.showSaveDialog(PerformanceResultDialog.this);
            if (JFileChooser.APPROVE_OPTION == result) {
                File file = fileChooser.getSelectedFile();
                try {
                    ChartUtilities.saveChartAsPNG(file, memoryChart, 1024, 768);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "error saving to file: " + e.getMessage());
                }
            }
        }

    });

    // memory chart
    memoryChart = getMemoryChart(data.getIntervalSize(), data.getMemory());

    // performance chart
    performanceChart = getPerformanceChart(data.getIntervalSize(), data.getPerformance(),
            data.getExpectedRevokedCount());

    Container container = getContentPane();
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    if (null != performanceChart) {
        splitPane.setTopComponent(new ChartPanel(performanceChart));
    }
    if (null != memoryChart) {
        splitPane.setBottomComponent(new ChartPanel(memoryChart));
    }
    splitPane.setDividerLocation(getHeight() / 2);
    splitPane.setDividerSize(1);
    container.add(splitPane);

    setVisible(true);
}

From source file:br.usp.poli.lta.cereda.macro.ui.Editor.java

/**
 * Construtor.//  www . j  a  va 2 s.c om
 */
public Editor() {

    // define as configuraes de exibio
    super("Expansor de macros");
    setPreferredSize(new Dimension(550, 550));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setResizable(false);
    setLayout(new MigLayout());

    // cria os botes e suas respectivas aes
    open = new JButton("Abrir",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/macro/images/open.png")));
    save = new JButton("Salvar",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/macro/images/save.png")));
    run = new JButton("Executar",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/macro/images/play.png")));
    clear = new JButton("Limpar",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/macro/images/clear.png")));

    // cria uma janela de dilogo para abrir e salvar arquivos de texto
    chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos de texto", "txt", "text");
    chooser.setFileFilter(filter);

    // ao de abertura de arquivo
    open.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            int value = chooser.showOpenDialog(Editor.this);
            if (value == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    String content = FileUtils.readFileToString(file);
                    input.setText(content);
                    output.setText("");
                } catch (Exception e) {
                }
            }
        }
    });

    // ao de salvamento de arquivo
    save.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            int value = chooser.showSaveDialog(Editor.this);
            if (value == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    FileUtils.writeStringToFile(file, input.getText(), Charset.forName("UTF-8"));
                    output.setText("");
                } catch (Exception e) {
                }
            }
        }
    });

    // ao de limpeza da janela de sada
    clear.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            output.setText("");
        }
    });

    // ao de execuo do expansor de macros
    run.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                output.setText(MacroExpander.parse(input.getText()));
            } catch (Exception exception) {
                String out = StringUtils.rightPad("ERRO: ", 50, "-").concat("\n");
                out = out.concat(WordUtils.wrap(exception.getMessage(), 50)).concat("\n");
                out = out.concat(StringUtils.repeat(".", 50)).concat("\n");
                output.setText(out);
            }
        }
    });

    // tela de entrada do texto
    input = new RSyntaxTextArea(14, 60);
    input.setCodeFoldingEnabled(true);
    input.setWrapStyleWord(true);
    input.setLineWrap(true);
    RTextScrollPane iinput = new RTextScrollPane(input);
    add(iinput, "span 4, wrap");

    // adiciona os botes
    add(open);
    add(save);
    add(run);
    add(clear, "wrap");

    // tela de sada da expanso
    output = new RSyntaxTextArea(14, 60);
    output.setEditable(false);
    output.setCodeFoldingEnabled(true);
    output.setWrapStyleWord(true);
    output.setLineWrap(true);
    RTextScrollPane ioutput = new RTextScrollPane(output);
    add(ioutput, "span 4");

    // ajustes finais
    pack();
    setLocationRelativeTo(null);

}

From source file:com.antelink.sourcesquare.gui.controller.SourceSquareController.java

public void bind() {

    this.view.getSelectButtonLabel().addMouseListener(new MouseListener() {

        @Override/*from w w  w.ja  v  a 2 s  . com*/
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseClicked(MouseEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileHidingEnabled(false);
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int showDialog = fileChooser.showDialog(SourceSquareController.this.view, "Select directory");
            if (showDialog == JFileChooser.APPROVE_OPTION) {
                SourceSquareController.this.view.getTextField()
                        .setText(fileChooser.getSelectedFile().getAbsolutePath());
            }

        }
    });

    this.view.getScanButtonLabel().addMouseListener(new MouseListener() {

        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseClicked(MouseEvent arg0) {
            File toScan = new File(SourceSquareController.this.view.getTextField().getText());
            if (!toScan.exists() || toScan.list().length == 0) {
                JOptionPane.showMessageDialog(SourceSquareController.this.view,
                        "Choose a valid and not empty directory", null, JOptionPane.ERROR_MESSAGE);
                return;
            }
            SourceSquareController.this.view.setVisible(false);
            SourceSquareController.this.eventBus.fireEvent(new StartScanEvent(toScan));

        }
    });

}

From source file:com.wet.wired.jsr.player.JPlayer.java

public void actionPerformed(ActionEvent ev) {

    if (ev.getActionCommand().equals("open")) {
        UIManager.put("FileChooser.readOnly", true);
        JFileChooser fileChooser = new JFileChooser();
        FileExtensionFilter filter = new FileExtensionFilter();

        filter = new FileExtensionFilter();
        filter.addExtension("owl");
        filter.setDescription("TestingOwl File");

        if (target != null) {
            fileChooser.setSelectedFile(new File(target + ".owl"));
        }/*from  www .  j  av  a  2s .c  o m*/
        fileChooser.setFileFilter(filter);
        fileChooser.setCurrentDirectory(new File("."));
        fileChooser.showOpenDialog(this);

        if (fileChooser.getSelectedFile() != null) {
            // target = fileChooser.getSelectedFile().getAbsolutePath();
            String targetCapOwl = fileChooser.getSelectedFile().getAbsolutePath();
            target = targetCapOwl.substring(0, targetCapOwl.lastIndexOf(".owl"));
            open();
        }
    } else if (ev.getActionCommand().equals("play")) {
        play();
    } else if (ev.getActionCommand().equals("reset")) {
        reset();
    } else if (ev.getActionCommand().equals("fastForward")) {
        fastForward();
    } else if (ev.getActionCommand().equals("pause")) {
        pause();
    } else if (ev.getActionCommand().equals("close")) {
        close();
    } else if (ev.getActionCommand().equals("recorder")) {
        closePlayer();
        Main.getRecorder().init(new String[0]);
    }
}

From source file:net.sf.webphotos.action.AcaoAdicionarFoto.java

/**
 * Mtodo responsvel pela ao de insero das fotos. Inicia um objeto
 * JFileChooser para a escolha do arquivo e faz a configurao. Testa se o
 * diretrio inicial  vlido e depois faz a implantao da foto. Atualiza a
 * tabela, ajusta as colunas, aciona o flag de
 * {@link net.sf.webphotos.gui.PainelWebFotos#alteracaoDetectada() alteracaoDetectada}()
 * e armazena o ltimo diretrio lido.//w  w w  .j  a va  2 s .  com
 *
 * @param e Evento da ao de adio de foto.
 */
@Override
public void actionPerformed(ActionEvent e) {
    fileChooser = new JFileChooser();
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setFileFilter(new ImageFilter());
    fileChooser.setDialogTitle(titulo);
    fileChooser.setApproveButtonText("Ok");
    fileChooser.setApproveButtonToolTipText("Adiciona as fotos selecionadas ao lbum");
    fileChooser.setMultiSelectionEnabled(true);

    if (diretorioInicial != null && diretorioInicial.isDirectory()) {
        fileChooser.setCurrentDirectory(diretorioInicial);
    }

    int retornoFc = fileChooser.showOpenDialog(null);

    if (retornoFc == JFileChooser.APPROVE_OPTION && fileChooser.getSelectedFiles().length > 0) {
        Album.getAlbum().adicionarFotos(fileChooser.getSelectedFiles());

        /**
         * aqui o codigo que atualiza a tabela
         */
        TableModelFoto.getModel().update();
        TableModelFoto.getModel().fireTableDataChanged();
        tbFotos.setModel(new TableSorter(TableModelFoto.getModel(), tbFotos.getTableHeader()));
        tbFotos.getColumnModel().getColumn(2)
                .setCellEditor(new javax.swing.DefaultCellEditor(lstCreditosTabelaFotos));

        /**
         * ajusta colunas
         */
        Util.ajustaLargura(tbFotos, larguraColunasFotos);
        tbFotos.repaint();

        /**
         * liga o flag de alterao realiza
         */
        PainelWebFotos.alteracaoDetectada();

        /**
         * armazena o ltimo diretrio lido
         */
        diretorioInicial = null;
        diretorioInicial = new File(fileChooser.getSelectedFiles()[0].getParent());
    }
}

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     *///  ww  w  .j  a va2s .  c  o m
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

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

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        final File file = chooser.getSelectedFile();

        new SwingWorker<Document, Void>() {
            protected Document doInBackground() throws Exception {
                if (builder == null) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    builder = factory.newDocumentBuilder();
                }
                return builder.parse(file);
            }

            protected void done() {
                try {
                    Document doc = get();
                    JTree tree = new JTree(new DOMTreeModel(doc));
                    tree.setCellRenderer(new DOMTreeCellRenderer());

                    setContentPane(new JScrollPane(tree));
                    validate();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(DOMTreeFrame.this, e);
                }
            }
        }.execute();
    }

From source file:org.obiba.onyx.jade.instrument.summitdoppler.VantageABIInstrumentRunner.java

public VantageABIInstrumentRunner() throws Exception {
    super();//from   ww  w.j  a v a  2  s . c om

    // Initialize interface components.
    saveButton = new JButton();
    saveButton.setMnemonic('S');
    // saveDataBtn.setEnabled(false);

    fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "Vantage ABI (.ABI)";
        }

        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().endsWith(".ABI");
        }
    });

    // Initialize interface components size
    appWindowWidth = 300;
    appWindowHeight = 175;
}