Opening files with JFileChooser
Asked Answered
G

3

6

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?

Global answered 27/11, 2011 at 3:32 Comment(3)
That method is on JFileChooser: choice.getSelectedFile();Lewiss
It should be choice.getSelectedFile(); Unfruitful
Is there anything better that JFileChooser. What if you want to make it look like it open in Microsoft Open box.Anguiano
B
10

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

choice.getSelectedFile()
Blemish answered 27/11, 2011 at 3:36 Comment(0)
M
3
  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);
        }

    }
}                                          
Mantelletta answered 9/2, 2014 at 17:59 Comment(1)
I recommend adding some descriptive text to explain the relevant sections of your code.Sikorsky
E
0
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
        });

    }
}
Escapade answered 7/2, 2015 at 15:6 Comment(2)
Adding a description would be helpful.Dentelle
My bad copy the code and run it. it opens a text file and saves it out.Escapade

© 2022 - 2024 — McMap. All rights reserved.