Reputation: 5
I am making a file opening wizard, and the JFileChooser is opened from a browse button on the initial window. I currently have it set up so that the browse button disposes of that first window and opens the JFileChooser window simultaneously. I would rather have the window be disposed after the user has selected their file in case they want to cancel and go back to the initial window - this is not currently possible.
Here's the relevant code:
class BrowseButton extends JButton {
public BrowseButton(String name, final JPanel pane) {
super(name);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("dwg files", "dwg");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(pane, "Open");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
String[] layers = getFileLayers(file.getPath());
openLayerWindow(layers);
}
}
});
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
}
and when the button is instantiated...
//Bottom Panel
final JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
BrowseButton browse = new BrowseButton("Browse...", bottom);
browse.setMnemonic(KeyEvent.VK_B);
CloseButton close = new CloseButton("Close");
close.setMnemonic(KeyEvent.VK_C);
bottom.add(close);
bottom.add(browse);
basic.add(bottom);
Upvotes: 0
Views: 633
Reputation: 47608
You can take advantage of SwingUtilities.getWindowAncestor
to retrieve the containing window of your BrowseButton
and dispose it only if the user choose the APPROVE_OPTION
.
class BrowseButton extends JButton {
public BrowseButton(String name, final JPanel pane) {
super(name);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("dwg files", "dwg");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(pane, "Open");
if (ret == JFileChooser.APPROVE_OPTION) {
SwingUtilities.getWindowAncestor(BrowsButton.this).dispose();
File file = fileopen.getSelectedFile();
String[] layers = getFileLayers(file.getPath());
openLayerWindow(layers);
}
}
});
}
Upvotes: 2