如何使用openFileChooser打开文本文件

问题描述 投票:1回答:2

我正在尝试通过菜单按钮打开文件,但无法找到使用动作监听器执行此操作的合适方法。为此,我需要对代码进行哪些补充?

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

}    
java actionlistener jfilechooser
2个回答
1
投票

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


0
投票

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

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
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");
}

}}

© www.soinside.com 2019 - 2024. All rights reserved.