how do I make jfilechooser only accept .txt
76,180
Solution 1
You need to add a filter:
JFileChooser jf = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
jf.setFileFilter(filter);
Solution 2
Here some examples
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.pdf", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.txt", "txt"));
Solution 3
You could do that by using FileFilter
.
Create a Filefilter
with the necessary conditions. Set this file filter to the JFileChooser
, and launch it.
Author by
Devendra Danny Ramdayal
Updated on June 08, 2020Comments
-
Devendra Danny Ramdayal almost 4 years
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(); } } } });