Frage

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:

// 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());
        }
    });
War es hilfreich?

Lösung 2

The Oracle example is pretty good in my opinion: 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);
    }

Andere Tipps

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

      }
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top