2013-03-19 34 views
0

打開一個文件fileItem1is的JMenuItem當我fileItem1,單擊這是你將如何使它打開一個文件,然後就顯示在JFrame中該文件的名稱:JFileChooser,以從JMenu的

// open file 
fileItem1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     JFileChooser chooser = new JFileChooser(); 
     Component parent = null; 
     int returnVal = chooser.showOpenDialog(parent); 
     if(returnVal == JFileChooser.APPROVE_OPTION) { 
       System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); 
      }    
      jStyledTextPane.setText("You chose to open this file: " + chooser.getSelectedFile().getName()); 
     } 
    }); 
+1

最後一個問題呢?好的,你已經刪除了它,但是在你告訴你想借助我發佈的鏈接自己試試這個之前......你應該花一些精力來代替使用SO作爲代碼生成器。 – Kai 2013-03-19 11:53:22

+0

我有,對不起,我掙扎了一下,但我管理得很好,這是任何人在未來需要的代碼。 – user2145688 2013-03-19 11:59:28

回答

0

Oracle的例子是在我看來還不錯:http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

下面是執行:

int returnVal = fc.showOpenDialog(FileChooserDemo.this); 

    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     File file = fc.getSelectedFile(); 
     //This is where a real application would open the file. 
     log.append("Opening: " + file.getName() + "." + newline); 
    } else { 
     log.append("Open command cancelled by user." + newline); 
    } 
1
fileItem1.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent event) { 
    JFileChooser fc = new JFileChooser(); 

    int returnVal = fc.showOpenDialog(YourClassName.this); 

    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     File file = fc.getSelectedFile(); 
     filePath = file.getAbsolutePath(); 
     try { 
     //your write to Jframe method 
     } catch (FileNotFoundException e) { 
     Logger.getLogger(YourClassName.class.getName()).log(
      Level.SEVERE, null, e); 
     } 

     } 
    } 
});