Opening files with JFileChooser

2019-01-26 11:22发布

问题:

As a little side project I'd thought it would cool to make a text editor. I'm currently stuck on opening files. This is my code for opening the file(e is an ActionEvent, open is a JMenuItem):

else if (e.getSource() == open) {
        JFileChooser choice = new JFileChooser();
        int option = choice.showOpenDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try{
                Scanner scan = new Scanner(new FileReader((open).getSelectedFile().getPath()));
            }
        }

    }

The try block is giving me the trouble. Eclipse is saying that getSelectedFile() is undefined for type JMenuItem. It also appears to be undefined for MenuItems as well. Is there another way to approach this, or another method that works the same?

回答1:

You need to call getSelectedFile() on the JFileChooser once it has returned, so change your code to:

choice.getSelectedFile()


回答2:

  private void selectfileActionPerformed(java.awt.event.ActionEvent evt) {                                           

    JFileChooser jFileChooser=new JFileChooser();
   StringBuffer buffer;
    buffer = new StringBuffer();
   int result= jFileChooser.showOpenDialog(this);
    if(result==JFileChooser.APPROVE_OPTION)
    {
        try {
            FileReader reader;
            reader = null;
            JOptionPane.showMessageDialog(this,"hii user clicked open sysytem");
            File file=jFileChooser.getSelectedFile();
            reader=new FileReader(file);
            int i=1;
            while(i!=-1)
            {
                i=reader.read();
                char ch=(char) i;
                buffer.append(ch);

            }

            notepad.setText(buffer.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}                                          


回答3:

import java.awt.EventQueue;

public class FileChooser extends JFrame
{
    private JPanel contentPane;
    String filename;
   // main
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    FileChooser frame = new FileChooser();
                    frame.setVisible(true);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public FileChooser()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        // button to selct file
        JButton btnNewButton = new JButton("Select file");
        btnNewButton.setBounds(10, 2, 89, 23);
        contentPane.add(btnNewButton);
        // area to display file content
        final JTextArea textArea = new JTextArea();
        textArea.setBounds(10, 36, 414, 215);
        contentPane.add(textArea);
         // save button
        final JButton btnSave = new JButton("Save");
        btnSave.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {

                try
                {
                    FileWriter writer = new FileWriter(filename.replace(".",
                            "_out."));
                    BufferedWriter bwr = new BufferedWriter(writer);

                    bwr.write(textArea.getText());

                    bwr.close();
                    writer.close();
                    System.out.println(textArea.getText());
                } catch (Exception e)
                {
                    System.out.println("Error");
                }
            }
        });
        btnSave.setBounds(283, 2, 89, 23);
        contentPane.add(btnSave);
      // listen to button clicks
        btnNewButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION)
                {
                    File selectedFile = fileChooser.getSelectedFile();
                    filename = selectedFile.getAbsolutePath();

                    try
                    {
                        FileReader reader = new FileReader(filename);
                        BufferedReader br = new BufferedReader(reader);
                        textArea.read(br, null);
                        br.close();
                        System.out.println(textArea.getText());

                    } catch (Exception e)
                    {
                        System.out.println("Error");
                    }enter code here

                }

            }
    enter code here
        });

    }
}