java - 使用 JFileChooser - 访问所选文件

标签 java swing scope 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);
    }
});

我似乎无法弄清楚如何从监听器外部访问"file",即在创建 GUI 其余部分的函数中。我在启动文件选择器的按钮旁边有一个空白文本标签,所以我想要做的是存储文件,并将文本标签的文本设置为文件名。

最佳答案

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

}

关于java - 使用 JFileChooser - 访问所选文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8402889/

相关文章:

java - 如何在android-java中解析xml?

java - 如果构造函数抛出异常,是否不调用 try-with-resources 习惯用法的 close 方法?

java - 我如何在java中处理Jcombobox的按键事件

java - 如何使用大小调整所有Graphics2D

c++游戏引擎设计和超出范围的对象

java - 如何返回与使用 Java 6 传入的类类型相同的对象的实例?

java - 如何为 JTable 中的单元格着色?

javascript - $scope 变量拒绝更改 wavesurfer 函数处理程序中的值

javascript - 在 jQuery 'click' 中创建的对象仍然存在,即使创建了一个新对象

java - 如何创建可以容纳图像或视频的 View ?