我有一个叫做"search“的按钮,它可以打开一个JFileChooser窗口。双击目录后,该窗口将自动关闭,因此无需单击取消或任何其他按钮。这有可能吗?
谢谢。
发布于 2015-02-09 18:00:03
您可以通过向JFileChooser添加PropertyChangeListener来完成此操作。在propertyChange()方法中,检查属性名是否为JFileChooser.DIRECTORY_CHANGED_PROPERTY。如果是,只需调用JFileChooser.approveSelection()方法即可关闭文件选择器对话框。
注意:由于选择文件夹将自动关闭文件选择器,在这种情况下,将文件选择器(用户)直接指向他/她可以选择所需文件夹的文件夹是很重要的。为此,使用JFileChooser的构造函数来设置初始/当前文件夹(您可以将文件夹作为File或String传递),也可以在构造函数之后通过调用JFileChooser.setCurrentDirectory()来设置它。
下面是一个完整的示例:
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("test");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
System.out.println("DIRECTORY CHANGED");
fc.approveSelection();
}
}
});
int result = fc.showOpenDialog(f);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Chosen folder: " + fc.getSelectedFile());
}
}
});
f.add(b);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);https://stackoverflow.com/questions/28406773
复制相似问题