you can hide the accept/cancel buttons by calling chooser.setControlButtonsAreShown(false) when detect any selecting change on files/directories:
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
myChooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File file = (File) evt.getNewValue();
if (file != null && file.isFile()) { // your condition
myChooser.setControlButtonsAreShown(false);
}
else if ( file != null ) {
System.out.println(file.getName());
myChooser.setControlButtonsAreShown(true);
}
}
myChooser.repaint();
}
});
but it may confuse the user, its better to make custom FileFilter and showing only the files/directories you need:
public static class MyDirectoryFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept( File file ) {
return file.isDirectory() && customeCondition(file) ;
}
@Override
public String getDescription() {
return "this only my custom dir";
}
}
myChooser.setFileFilter( new MyDirectoryFilter () );
Edit:
I found a way to disable the button, by iterating over the components and getting handle to Open button :
http://www.coderanch.com/t/468663/GUI/java/Disabling-Enabling-level-button-folder
example:
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
myChooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File file = (File) evt.getNewValue();
if (file != null && file.isFile()) {
setOpenButtonState(myChooser, false);
}
else if ( file != null ) {
setOpenButtonState(myChooser, true);
System.out.println(file.getName());
}
}
myChooser.repaint();
}
});
public static void setOpenButtonState(Container c, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if ( "Open".equals(b.getText()) ) {
b.setEnabled(flag);
}
} else if (comp instanceof Container) {
setOpenButtonState((Container) comp, flag);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…