java JFileChooser 从 JMenu 打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15498709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:49:09  来源:igfitidea点击:

JFileChooser to open a file from a JMenu

javafilejfilechooserjmenu

提问by user2145688

fileItem1is a JMenuItem when i click on fileItem1, this is how you would make it open a file and then just display the name of that file in the JFrame:

当我点击 fileItem1 时,fileItem1 是一个 JMenuItem,这就是你如何让它打开一个文件,然后在 JFrame 中显示该文件的名称:

// open file
fileItem1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        Component parent = null;
        int returnVal = chooser.showOpenDialog(parent);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
               System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
            }               
            jStyledTextPane.setText("You chose to open this file: " + chooser.getSelectedFile().getName());
        }
    });

采纳答案by oblivion19

The Oracle example is pretty good in my opinion: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

我认为 Oracle 示例非常好:http: //docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Here is the implementation:

这是实现:

    int returnVal = fc.showOpenDialog(FileChooserDemo.this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        //This is where a real application would open the file.
        log.append("Opening: " + file.getName() + "." + newline);
    } else {
        log.append("Open command cancelled by user." + newline);
    }

回答by Cugomastik

fileItem1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
    JFileChooser fc = new JFileChooser();

    int returnVal = fc.showOpenDialog(YourClassName.this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        filePath = file.getAbsolutePath();
        try {
        //your write to Jframe method
        } catch (FileNotFoundException e) {
        Logger.getLogger(YourClassName.class.getName()).log(
            Level.SEVERE, null, e);
        }

      }
    }
});