JFileChooser组件显示怪异

时间:2012-05-12 09:35:52

标签: java swing jfilechooser

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

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);
    }

}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

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