2011-12-06 9 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変数をanon内部クラスの代わりにクラスレベルで定義することはどうですか?

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

} 
関連する問題