2011-12-06 65 views
1

沒有編碼,所以覺得我有點生疏。我正在嘗試構建一個讓用戶選擇文件作爲輸入的應用程序。下面的代碼位是我的時刻:使用JFileChooser - 獲取對選定文件的訪問

JButton btnFile = new JButton("Select Excel File"); 
btnFile.addActionListener(new ActionListener() { 
    //Handle open button action. 
    public void actionPerformed(ActionEvent e) { 
     final JFileChooser fc = new JFileChooser(); 
     int returnVal = fc.showOpenDialog(frmRenamePdfs); 
     if (returnVal == JFileChooser.APPROVE_OPTION) { 
      File file = fc.getSelectedFile(); 
      //This is where a real application would open the file. 
      System.out.println("File: " + file.getName() + ".");  
     } else { 
      System.out.println("Open command cancelled by user."); 
     } 
     System.out.println(returnVal); 
    } 
}); 

我似乎無法弄清楚如何在函數可以訪問「文件」來自監聽器之外,即在休息GUI被創建。我在啓動文件選擇器的按鈕旁邊有一個空白文本標籤,所以我想要做的是存儲文件,並將文本標籤的文本設置爲文件的名稱。

回答

3

如何在類級別定義File file變量而不是內部匿名內部類?

public class SwingSandbox { 

    private File file; 

    public SwingSandbox() { 
    final JFrame frame = new JFrame("Hello"); 

    JButton btnFile = new JButton("Select Excel File"); 
    btnFile.addActionListener(new ActionListener() { 
     //Handle open button action. 
     public void actionPerformed(ActionEvent e) { 
      final JFileChooser fc = new JFileChooser(); 
      int returnVal = fc.showOpenDialog(frame); 
      if (returnVal == JFileChooser.APPROVE_OPTION) { 
       file = fc.getSelectedFile(); 
       //This is where a real application would open the file. 
       System.out.println("File: " + file.getName() + ".");  
      } else { 
       System.out.println("Open command cancelled by user."); 
      } 
      System.out.println(returnVal); 
     } 
    }); 

    frame.getContentPane().add(btnFile); 
    frame.setSize(100, 100); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    } 


    public static void main(String[] args) throws Exception { 
    new SwingSandbox(); 
    } 

} 
相關問題