1

我正在尝试从菜单按钮打开文件,但我无法找到合适的方法来使用动作侦听器执行此操作。我需要对此代码进行哪些补充才能做到这一点?

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

2 回答 2

2

假设您已经知道如何创建 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 {                
        }
    }
}

有关更多详细信息,请参阅此链接:OracleFileChooserDocument

于 2020-01-09T07:44:20.313 回答
-1

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

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");
    }
}
    } 
于 2020-01-09T17:45:09.340 回答