Good afternoon all,
I have an instance of a javax.swing.JFileChooser and I added a few choosable javax.swing.FileFilters using addChoosableFileFilter.
However when I show the dialog (through showSaveDialog), my custom choosable FileFilter is not selected by default.
I wanted to select the filter "Image Files" by default..
How do we select a default filter for the javax.swing.JFileChooser dialog?
SSCCEd:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new java.lang.Runnable() {
@Override
public void run() {
new javax.swing.JFrame() {
{
final javax.swing.JButton button = new javax.swing.JButton("Save");
button.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
new javax.swing.JFileChooser() {
{
addChoosableFileFilter(NewFileFilter("Text Files", new String[] { "txt" }));
addChoosableFileFilter(NewFileFilter("Image Files", new String[] { "gif", "png", "jpg" }));
addChoosableFileFilter(NewFileFilter("Audio Files", new String[] { "mp3" }));
addChoosableFileFilter(NewFileFilter("Video Files", new String[] { "mp4", "avi" }));
showSaveDialog(button);
}
private javax.swing.filechooser.FileFilter NewFileFilter(final String desc, final String[] allowed_extensions) {
return new javax.swing.filechooser.FileFilter() {
@Override
public boolean accept(java.io.File f) {
if (f.isDirectory()) {
return true;
}
int pos = f.getName().lastIndexOf('.');
if (pos == -1) {
return false;
} else {
String extension = f.getName().substring(pos + 1);
for (String allowed_extension : allowed_extensions) {
if (extension.equalsIgnoreCase(allowed_extension)) {
return true;
}
}
return false;
}
}
@Override
public String getDescription() {
return desc;
}
};
}
};
}
});
add(button);
setSize(100, 100);
setVisible(true);
}
};
}
});
}