2

我试图在文件选择器对话框中打开一个文件,但是,当我打开一个文件或只是关闭对话框时。对话框再次出现,我必须关闭它两次。这是我的代码,不知道有什么问题

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try {
        // TODO add your handling code here:
        ObjectInputStream input;
        JFileChooser openFileChooser = new JFileChooser();
        openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
        openFileChooser.showOpenDialog(null);
        openFileChooser.setCurrentDirectory(new File("."));
        if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
            input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
            input.close();
        }
        javax.swing.JFrame openFileFrame = new javax.swing.JFrame();        
        openFileFrame.setLayout(new BorderLayout());
        openFileFrame.setLocationRelativeTo(null);
        openFileFrame.add(openFileChooser, BorderLayout.CENTER);
        openFileFrame.pack();
        openFileFrame.setVisible(true);
    } catch (IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }

}
4

2 回答 2

2

此代码行创建第一个

JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
   input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
   input.close();
}

其余代码行嵌入第二个

javax.swing.JFrame openFileFrame = new javax.swing.JFrame();        
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
于 2012-05-12T09:45:15.007 回答
1

删除第一次出现的 openFileChooser.showOpenDialog(null);

于 2012-05-12T10:02:33.703 回答