正如 Wajdy Essam 已经回答的那样,您通常可以使用隐藏/显示控制按钮
javax.swing.JFileChooser#setControlButtonsAreShown(boolean)
但是这种方法并不适用于所有的 Look&Feel,至少不是我正在使用的那些。
我写了一个在大多数情况下都可以使用的快速解决方法。
此外,您可以完全访问 FileChooser 的取消和批准按钮。
public class JFileChooserTest extends JFileChooser {
private JButton approveButton, cancelButton;
public JFileChooserTest() {
// Lookup the Buttons
if (approveButton == null) {
approveButton = lookupButton(JFileChooserTest.this, getUI().getApproveButtonText(this));
}
if (cancelButton == null) {
cancelButton = lookupButton(JFileChooserTest.this, UIManager.getString("FileChooser.cancelButtonText"));
}
setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//Creating the Listener
PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
//Do action only if the selected file changed
if (evt.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File newFile = (File) evt.getNewValue();
//Validate the new File
boolean validate = validateFile(newFile);
//Enable/Disable the buttons
if (approveButton != null) {
approveButton.setEnabled(validate);
}
if (cancelButton != null) {
cancelButton.setEnabled(validate);
}
}
}
};
//Adding the listeners
addPropertyChangeListener(SELECTED_FILE_CHANGED_PROPERTY, propertyChangeListener);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFileChooserTest test = new JFileChooserTest();
test.showOpenDialog(null);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(JFileChooserTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/**
* Simple validation method; only for testing purpose
*
* @param f
* @return
*/
private boolean validateFile(File f) {
return f != null && !f.getName().startsWith("A");
}
/**
* Looksup the first JButton in the specific Container (and sub-containers)
* with the given text.
*
* @param c
* @param text
* @return
*/
private JButton lookupButton(Container c, String text) {
JButton temp = null;
for (Component comp : c.getComponents()) {
if (comp == null) {
continue;
}
if (comp instanceof JButton && (temp = (JButton) comp).getText() != null && temp.getText().equals(text)) {
return temp;
} else if (comp instanceof Container) {
if ((temp = lookupButton((Container) comp, text)) != null) {
return temp;
}
}
}
return temp;
}
}
我还建议使用javax.swing.filechooser.FileFilter来验证选定的文件,而不是覆盖approveSelection()