0

当我单击 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());
        }
    });
4

2 回答 2

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

      }
    }
});
于 2014-03-06T13:25:23.893 回答
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);
    }
于 2013-03-19T12:01:34.123 回答