Example usage for javax.swing JFileChooser APPROVE_OPTION

List of usage examples for javax.swing JFileChooser APPROVE_OPTION

Introduction

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

Prototype

int APPROVE_OPTION

To view the source code for javax.swing JFileChooser APPROVE_OPTION.

Click Source Link

Document

Return value if approve (yes, ok) is chosen.

Usage

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.time.pages.TimeFileSelectionPage.java

@Override
public JButton getSelectInputFileButton() {
    if (selectInputFileButton == null) {
        selectInputFileButton = new JButton(Icons.IC_MIME_CSV_SMALL);
        selectInputFileButton.setText("Select Data File");

        selectInputFileButton.addActionListener(new ActionListener() {

            @Override// ww w  . j  a  va  2s  .  c  o m
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                JFileChooser fc = getFileChooser();
                if (dataFile != null)
                    fc.setCurrentDirectory(dataFile.getParentFile());
                int returnValue = fc.showOpenDialog(parent);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    dataFile = fc.getSelectedFile();
                    getInputFileTextField().setText(dataFile.getName());
                    // TODO check if that file contains a time column
                    if (checkFile()) {
                        plotWizard.setDataFile(dataFile);
                    } else {
                        plotWizard.setDataFile(null);
                    }
                }
            }
        });
    }
    return selectInputFileButton;
}

From source file:PreferencesTest.java

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

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

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);/*from  w w w .  ja  v a2  s .  c  om*/

    // set up file chooser that shows XML files

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

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

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

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

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

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

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

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     *//*from w  ww  . j a v a  2 s  .  co 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:modelibra.swing.app.util.FileSelector.java

/**
 * Gets the saved file given a file path.
 * /*from  www.  ja v  a  2  s.c om*/
 * @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: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.//from  w ww. j  a v a 2  s .  c  o m
 *
 * @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:br.usp.poli.lta.cereda.wsn2spa.Editor.java

public Editor() {
    super("WSN2SPA");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setResizable(false);//www . j a  va 2 s  .  c  o  m
    setLayout(new MigLayout());

    txtDotOutput = new JTextField(15);
    txtYamlOutput = new JTextField(15);
    txtFile = new JTextField(10);
    txtFile.setEditable(false);

    checkDFAConvert = new JCheckBox("Convert submachines to DFA's");
    checkMinimize = new JCheckBox("Apply state minimization");
    checkMinimize.setEnabled(false);
    btnOpen = new JButton(
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/open.png")));
    btnRun = new JButton("Convert WSN to SPA",
            new ImageIcon(getClass().getResource("/br/usp/poli/lta/cereda/wsn2spa/images/play.png")));

    chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt", "text");
    chooser.setFileFilter(filter);

    btnOpen.addActionListener((ActionEvent ae) -> {
        int value = chooser.showOpenDialog(Editor.this);
        if (value == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
            txtFile.setText(file.getName());
        }
    });

    checkDFAConvert.addChangeListener((ChangeEvent ce) -> {
        checkMinimize.setEnabled(checkDFAConvert.isSelected());
        if (!checkDFAConvert.isSelected()) {
            checkMinimize.setSelected(false);
        }
    });

    btnRun.addActionListener((ActionEvent ae) -> {
        boolean restore = checkMinimize.isEnabled();
        state(false, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        try {
            if (!filled(txtDotOutput, txtYamlOutput, txtFile)) {
                throw new Exception(
                        "The fields could not be empty. Make " + "sure to select the grammar file and provide "
                                + "both DOT and YAML patterns in their respective " + "fields.");
            }
            if (!valid(txtDotOutput, txtYamlOutput)) {
                throw new Exception(
                        "The DOT and YAML fields lack the " + "replacement pattern '%s' in order to generate "
                                + "files corresponding to each submachine in the "
                                + "automaton model. Make sure to include the " + "pattern.");
            }
            if (!file.exists()) {
                throw new Exception("The provided grammar file '" + "' does"
                        + " not exist. Make sure the location is correct and" + " try again.");
            }

            String text = FileUtils.readFileToString(file, "UTF-8").trim();
            WirthLexer wl = new WirthLexer(text);
            Generator g = new Generator(wl);
            g.generateAutomaton();

            Writer writer = new Writer(g.getTransitions());
            Map<String, String> map = writer.generateYAMLMap(txtYamlOutput.getText().trim());

            if (Utils.neither(checkDFAConvert, checkMinimize)) {
                br.usp.poli.lta.cereda.wirth2ape.dot.Dot dot = new br.usp.poli.lta.cereda.wirth2ape.dot.Dot(
                        g.getTransitions());
                dot.generate(txtDotOutput.getText().trim());
                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            } else {
                for (String key : map.keySet()) {
                    Triple<Integer, Set<Integer>, List<SimpleTransition>> spec = Reader.read(map.get(key));
                    br.usp.poli.lta.cereda.nfa2dfa.dot.Dot dot = new br.usp.poli.lta.cereda.nfa2dfa.dot.Dot();
                    dot.append(Reader.getName(), "original", spec);

                    Conversion c;

                    if (checkDFAConvert.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.convert();
                        dot.append(Reader.getName().concat("'"), "converted", spec);
                    }

                    if (checkMinimize.isSelected()) {
                        c = new Conversion(spec.getThird(), spec.getFirst(), spec.getSecond());
                        spec = c.minimize();
                        dot.append(Reader.getName().concat("''"), "minimized", spec);
                    }

                    Yaml yaml = new Yaml();
                    Spec result = Utils.toFormat(spec);
                    result.setName(Reader.getName());
                    map.put(key, yaml.dump(result));

                    String dotname = String.format(txtDotOutput.getText().trim(), Reader.getName());
                    dot.dump(dotname);

                }

                for (String key : map.keySet()) {
                    FileUtils.write(new File(key), map.get(key), "UTF-8");
                }
            }

            showMessage("Success!", "The structured pushdown automaton "
                    + "spec was successfully generated from the provided " + "grammar file.");

        } catch (Exception exception) {
            showException("An exception was thrown", exception);
        }
        state(true, txtDotOutput, txtYamlOutput, btnOpen, btnRun, checkDFAConvert, checkMinimize);
        checkMinimize.setEnabled(restore);
    });

    add(new JLabel("Grammar file:"));
    add(txtFile);
    add(btnOpen, "growx, wrap");
    add(new JLabel("DOT pattern:"));
    add(txtDotOutput, "growx, span 2, wrap");
    add(new JLabel("YAML pattern:"));
    add(txtYamlOutput, "growx, span 2, wrap");
    add(checkDFAConvert, "span 3, wrap");
    add(checkMinimize, "span 3, wrap");
    add(btnRun, "growx, span 3");

    pack();
    setLocationRelativeTo(null);

}

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   ww w  .  j ava2s  . com*/
        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:it.unibas.spicygui.controllo.spicy.ActionLoadComaCorrespondences.java

@Override
public void performAction() {
    executeInjection();/*from  ww  w  .  ja  va  2  s  .c  o  m*/
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    if (mappingTask.getCandidateCorrespondences().size() != 0 && mappingTask.isToBeSaved()) {
        NotifyDescriptor notifyDescriptor = new NotifyDescriptor.Confirmation(
                NbBundle.getMessage(Costanti.class, Costanti.DISCARD_CANDIDATE_CORRESPONDENCES),
                DialogDescriptor.YES_NO_OPTION);
        DialogDisplayer.getDefault().notify(notifyDescriptor);
        if (notifyDescriptor.getValue().equals(NotifyDescriptor.NO_OPTION)
                || notifyDescriptor.getValue().equals(NotifyDescriptor.CLOSED_OPTION)) {
            return;
        }
    }
    mappingTask.clearCandidateCorrespondences();

    JFileChooser chooser = vista.getFileChooserApriTXT();
    File file;
    int returnVal = chooser.showOpenDialog(WindowManager.getDefault().getMainWindow());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            String absoluteFile = file.getPath();
            List<ValueCorrespondence> valueCorrespondences = dAOComaCorrespondences.loadComaCorrespondences(
                    absoluteFile, mappingTask.getSourceProxy().getDataSource(),
                    mappingTask.getTargetProxy().getDataSource());

            mappingTask.setCandidateCorrespondences(valueCorrespondences);

            SpicyTopComponent spicyTopComponent = scenario
                    .getSpicyTopComponent();/*SpicyTopComponent.findInstance();*/
            if (spicyTopComponent.getJLayeredPane().isAnalizzato()) {
                spicyTopComponent.drawConnections();
            } else {
                spicyTopComponent.drawScene();
            }
            spicyTopComponent.resetSlider();
            actionViewSpicy.performAction();
            spicyTopComponent.creaSlider();
            enableActions();
            IOProvider.getDefault().getIO(Costanti.FLUSSO_SPICY, false).select();
            if (logger.isDebugEnabled())
                logger.debug("--------------Candidate correspondences---------------");
            for (ValueCorrespondence correspondence : mappingTask.getCandidateCorrespondences()) {
                logger.info(correspondence);
            }
            return;

        } catch (DAOException ex) {
            DialogDisplayer.getDefault()
                    .notify(new NotifyDescriptor.Message(
                            NbBundle.getMessage(Costanti.class, Costanti.OPEN_ERROR) + " : " + ex.getMessage(),
                            DialogDescriptor.ERROR_MESSAGE));
            logger.error(ex);
        }
    }
}

From source file:com.bwc.ora.OraUtils.java

public static File selectFile(boolean openDialog, Component parent, int selectorType, String selectDescription,
        String extensionDescription, String... extentions) {
    File prevLocation = fc.getSelectedFile() != null ? fc.getSelectedFile().getParentFile() : null;

    fc = new JFileChooser(prevLocation);
    fc.setMultiSelectionEnabled(false);//from www .  j a  v a 2 s  .  c o m
    fc.setFileSelectionMode(selectorType);
    if (selectorType == JFileChooser.FILES_ONLY) {
        fc.setFileFilter(new FileNameExtensionFilter(extensionDescription, extentions));
    }
    fc.setAcceptAllFileFilterUsed(false);
    fc.setApproveButtonText("Select");
    fc.setDialogTitle("Select " + selectDescription + "...");
    int returnVal = openDialog ? fc.showOpenDialog(parent) : fc.showSaveDialog(parent);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (selectorType == JFileChooser.FILES_ONLY) {
            System.out.println("pwd: " + fc.getCurrentDirectory());
            return openDialog ? loadFile(fc.getSelectedFile()) : fc.getSelectedFile();
        } else if (selectorType == JFileChooser.DIRECTORIES_ONLY) {
            return loadDir(fc.getSelectedFile());
        } else {
            throw new IllegalArgumentException(
                    "Can't handle loading of files or directories at the same time!");
        }
    } else {
        return null;
    }
}

From source file:DesktopAppTest.java

public DesktopAppFrame() {
    setLayout(new GridBagLayout());
    final JFileChooser chooser = new JFileChooser();
    JButton fileChooserButton = new JButton("...");
    final JTextField fileField = new JTextField(20);
    fileField.setEditable(false);/*from   w  ww . j  a va2  s  .co m*/
    JButton openButton = new JButton("Open");
    JButton editButton = new JButton("Edit");
    JButton printButton = new JButton("Print");
    final JTextField browseField = new JTextField();
    JButton browseButton = new JButton("Browse");
    final JTextField toField = new JTextField();
    final JTextField subjectField = new JTextField();
    JButton mailButton = new JButton("Mail");

    openButton.setEnabled(false);
    editButton.setEnabled(false);
    printButton.setEnabled(false);
    browseButton.setEnabled(false);
    mailButton.setEnabled(false);

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN))
            openButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.EDIT))
            editButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.PRINT))
            printButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.BROWSE))
            browseButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.MAIL))
            mailButton.setEnabled(true);
    }

    fileChooserButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chooser.showOpenDialog(DesktopAppFrame.this) == JFileChooser.APPROVE_OPTION)
                fileField.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    });

    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().open(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    editButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().edit(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    printButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().print(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    browseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI(browseField.getText()));
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    mailButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String subject = percentEncode(subjectField.getText());
                URI uri = new URI("mailto:" + toField.getText() + "?subject=" + subject);

                System.out.println(uri);
                Desktop.getDesktop().mail(uri);
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    JPanel buttonPanel = new JPanel();
    ((FlowLayout) buttonPanel.getLayout()).setHgap(2);
    buttonPanel.add(openButton);
    buttonPanel.add(editButton);
    buttonPanel.add(printButton);

    add(fileChooserButton, new GBC(0, 0).setAnchor(GBC.EAST).setInsets(2));
    add(fileField, new GBC(1, 0).setFill(GBC.HORIZONTAL));
    add(buttonPanel, new GBC(2, 0).setAnchor(GBC.WEST).setInsets(0));
    add(browseField, new GBC(1, 1).setFill(GBC.HORIZONTAL));
    add(browseButton, new GBC(2, 1).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("To:"), new GBC(0, 2).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(toField, new GBC(1, 2).setFill(GBC.HORIZONTAL));
    add(mailButton, new GBC(2, 2).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("Subject:"), new GBC(0, 3).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(subjectField, new GBC(1, 3).setFill(GBC.HORIZONTAL));

    pack();
}