我正在尝试添加一个JFileChooser,它选择一个父目录并允许用户输入一个文件的名称。我知道showSaveDialog和showOpenDialog方法,但是我不想创建一个新窗口。
到目前为止,我的情况如下:
public class BrowserTest extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BrowserTest frame = new BrowserTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BrowserTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JFileChooser browser = new JFileChooser();
browser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "A .extension file";
}
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
browser.setDialogType(JFileChooser.SAVE_DIALOG);
browser.setSelectedFile(new File("*.extension"));
browser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String action = e.getActionCommand();
if(action.equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("trigger");
File f = browser.getCurrentDirectory();
System.out.println(f);
}
if(action.equals(JFileChooser.CANCEL_SELECTION))
JOptionPane.showConfirmDialog(null, "Start without saving?", "No save directory selected.", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
}
});
contentPane.add(browser);
revalidate();
}
}由于某些原因,按下“保存”按钮只能在选择文件时执行System.out.println("trigger");。是否有办法直接收听保存按钮按下?
发布于 2019-08-16 18:06:43
我刚刚发现问题就在browser.setSelectedFile(new File("*.extension"));行中。显然,这个方法不喜欢星号,用其他任何东西替换它都会解决问题。例如:browser.setSelectedFile(new File("new.extension"));将按预期工作。
发布于 2019-08-15 18:58:59
您可以使用以下代码访问文件选择器的默认按钮,然后将自己的侦听器添加到该按钮中:
JButton defaultButton = browser.getUI().getDefaultButton(browser);发布于 2019-08-15 19:13:38
如前所述,一种简单的解决方案是递归地遍历JFileBrowser的组件,直到找到正确的组件为止,这里有一个带有操作命令字符串"Open“的JButton。
例如,此方法可以工作:
public static void recursiveComponentSearch(Component c, String actionCommand,
ActionListener listener) {
if (c instanceof JButton) {
JButton button = (JButton) c;
// TODO: delete the line below
System.out.printf("Text: \"%s\"; action command: \"%s\"%n", button.getText(),
button.getActionCommand());
if (button.getActionCommand().equalsIgnoreCase(actionCommand)) {
button.addActionListener(listener);
}
}
// recursive search here
if (c instanceof Container) {
Container container = (Container) c;
Component[] components = container.getComponents();
for (Component component : components) {
recursiveComponentSearch(component, actionCommand, listener);
}
}
}用于:
ActionListener listener = evt -> System.out.println("Save button here");
String actionCommand = "Open";
recursiveComponentSearch(browser, actionCommand, listener);https://stackoverflow.com/questions/57514452
复制相似问题