如何使用 openFileChooser 打开文本文件

How to open a text file using openFileChooser

我正在尝试通过菜单按钮打开文件,但找不到合适的方法来使用动作侦听器执行此操作。我需要对此代码添加哪些内容才能执行此操作?

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    int returnValue = openFileChooser.showOpenDialog(this);
    if (returnValue == JFileChooser.APPROVE_OPTION){
        JOptionPane.showMessageDialog(null, "This a vaild file", 
                                            "Display Message", 
                                            JOptionPane.INFORMATION_MESSAGE);
    }
    else {
        JOptionPane.showMessageDialog(null, "No file was selected", 
                                            "Display Message",
                                            JOptionPane.INFORMATION_MESSAGE);
    }
}    

假设您已经知道如何创建 UI。所以首先你需要定义一个 JFileChooser 对象:

//Create a file chooser as final
final JFileChooser fc = new JFileChooser();

在你的事件方法中只需要处理动作:

public void actionPerformed(ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(YourClassName.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //What to do with the file here.                
        } else {                
        }
    }
}

请参阅此 link 了解更多详细信息:OracleFileChooserDocument

我能够完成这项工作,下面的代码将允许您从文件选择器中 select 一个文件,然后显示该文件。

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    System.out.println("Selected file: " + selectedFile.getAbsolutePath());
    try {
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + selectedFile.getAbsolutePath());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error");
    }
}
    }