我正在创建一个文件打开向导,并从初始窗口的浏览按钮打开JFileChooser。我目前设置它,以便浏览按钮处理第一个窗口并同时打开JFileChooser窗口。我希望在用户选择了他们的文件之后处理窗口,以防他们想要取消并返回初始窗口 - 目前这是不可能的。
以下是相关代码:
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();
}
});
}
当按钮被实例化时......
//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);
答案 0 :(得分:2)
您可以利用SwingUtilities.getWindowAncestor
检索BrowseButton
的包含窗口,并仅在用户选择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);
}
}
});
}