JFileChooser从JMenu打开一个文件

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

当我点击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());
        }
    });
java file jfilechooser jmenu
2个回答
0
投票

在我看来,Oracle的例子相当不错:http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

这是实施:

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

1
投票
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);
        }

      }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.