📄 e905. listening for approve and cancel events in a jfilechooser dialog.txt
字号:
When the user clicks on the approve button (Open or Save) or the Cancel button, an action event is fired.
Unfortunately, if the user clicks on the close-dialog icon in the title bar, an event is not fired. In order to listen for this event, it is necessary to add a window event listener to the dialog. This means that JFileChooser.showDialog() cannot be used because it creates the dialog internally. The workaround is to override the createDialog() method to make it public and then call it to create the dialog.
With this deficiency, we recommend that you simply wait until showDialog() returns and then use its return value. See e890 Determining If the Approve or Cancel Button Was Clicked in a JFileChooser Dialog for more information.
// Create customized chooser
MyFileChooser chooser = new MyFileChooser();
// Set dialog type if not OPEN_DIALOG
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
// Create dialog containing the chooser
final JDialog dialog = chooser.createDialog(frame);
// Add listener for approve and cancel events
chooser.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = (JFileChooser)evt.getSource();
if (JFileChooser.APPROVE_SELECTION.equals(evt.getActionCommand())) {
// Open or Save was clicked
// Hide dialog
dialog.setVisible(false);
} else if (JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) {
// Cancel was clicked
// Hide dialog
dialog.setVisible(false);
}
}
});
// Add listener for window closing events
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// Close-dialog icon was clicked
// Hide dialog
dialog.setVisible(false);
}
});
// Show the dialog; wait until dialog is closed
dialog.show();
// This version of JFileChooser simply makes createDialog a public method.
public class MyFileChooser extends JFileChooser {
public JDialog createDialog(Component parent) throws HeadlessException {
return super.createDialog(parent);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -