how do I make jfilechooser only accept .txt

Devendra Danny Ramdayal picture Devendra Danny Ramdayal · Apr 2, 2013 · Viewed 71.9k times · Source

I trying to save my contact in my table but filechosser always setit to all file. is there way I can set it to accept .txt only and make it default or the only option.

savecontact.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JFileChooser filesave = new JFileChooser();
        int returnVal = filesave.showSaveDialog(Main.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                File file = filesave.getSelectedFile();

                PrintWriter os = new PrintWriter(file);
                os.println("");
                for (int col = 0; col < table.getColumnCount(); col++) {
                    os.print(table.getColumnName(col) + "\t");
                }
                os.println("");
                os.println("");

                for (int row = 0; row < table.getRowCount(); row++) {
                    for (int col = 0; col < table.getColumnCount(); col++) {
                        os.print(table.getColumnName(col));
                        os.print(": ");
                        os.println(table.getValueAt(row, col));
                    }
                    os.println("");
                }
                os.close();
                System.out.println("Done!");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
});

Answer

Marcelo Tataje picture Marcelo Tataje · Apr 2, 2013

You need to add a filter:

JFileChooser jf = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
jf.setFileFilter(filter);