如何使 jfilechooser 只接受.txt

2022-09-01 03:28:37

我试图将我的联系人保存在我的表中,但文件选择器总是设置为所有文件。有没有办法,我可以将其设置为仅接受.txt,并将其设置为默认或唯一选项。

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();
            }
        }
    }
});

答案 1

您需要添加过滤器:

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

答案 2

这里有一些例子

fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.pdf", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.txt", "txt"));