【问题标题】:Working with JFileChooser - getting access to the selected file使用 JFileChooser - 访问所选文件
【发布时间】:2011-12-06 16:00:13
【问题描述】:

已经有一段时间没有编码了,所以我觉得我有点生疏了。我正在尝试构建一个允许用户选择文件作为输入的应用程序。以下代码是我目前拥有的:

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 其余部分的函数中。我在启动文件选择器的按钮旁边有一个空白文本标签,所以我要做的是存储文件,并将文本标签的文本设置为文件名。

【问题讨论】:

    标签: java swing scope jfilechooser


    【解决方案1】:

    如何在类级别而不是在匿名内部类中定义您的 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();
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      相关资源
      最近更新 更多