cool king
cool king

Reputation: 26

How do I read the contents of a txt file to a text area?

I want to read the contents of a text file into the text area of the application. The text area is showing up empty and I can't type anything into it. I am new to Swing.

This is the code I use:

class Menu implements ActionListener
{
    JLabel jlab;

    Menu()
    {
        JFrame jfrm = new JFrame("Menudemo");
        jfrm.setLayout(new FlowLayout());
        jfrm.setSize(720, 700);

        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
         JTextArea edit = new JTextArea("HI I AM A TEXTAREA",520,500);
        edit.setEditable(true);
        JScrollPane sta = new JScrollPane(edit);

        sta.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        sta.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        jlab = new JLabel();

        JMenuBar jmb = new JMenuBar();

        JMenu jmfile = new JMenu("File");
        JMenuItem jmiopen = new JMenuItem("Open");
        JMenuItem jmiclose = new JMenuItem("Close");
        JMenuItem jmisave = new JMenuItem("Save");
        JMenuItem jmiexit = new JMenuItem("Exit");
        jmfile.add(jmiopen);
        jmfile.add(jmiclose);
        jmfile.add(jmisave);
        jmfile.add(jmiexit);
        jmb.add(jmfile);

   //i want to open a file through the dialog box and load the content into the 
   //text area
        jmiopen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae)
            {
                 try{
                      File selectedFile = jfc.getSelectedFile();

                        int returnvalue = jfc.showOpenDialog(null);

                        if(returnvalue == JFileChooser.APPROVE_OPTION)
                        {
                        FileReader reader = new 
                        FileReader(selectedFile.getAbsolutePath());

                        @SuppressWarnings("resource")
                        BufferedReader br = new BufferedReader(reader);
                        String line = br.readLine();
                        while(line != null)
                        {
                            edit.append(line);
                           line=br.readLine();
                        }
                        /*ja.read(br,null);
                        br.close();
                        ja.requestFocus();
                        */
                       }
                 }
                 catch(Exception e2)
                    {
                        System.out.println(e2);
                    }
             }
        });
        jmiclose.addActionListener(this);
        jmisave.addActionListener(this);
        jmiexit.addActionListener(new ActionListener(){
            @Override
             public void actionPerformed(ActionEvent ae){
                System.exit(0);
            }
        });
        jfrm.add(edit);
        jfrm.add(sta);

        jfrm.add(jlab);
        jfrm.setJMenuBar(jmb);
        jfrm.setVisible(true);
  }

    public static void main(String args [])
    {
         SwingUtilities.invokeLater(new Runnable(){
             public void run()
             {
                 new Menu();
             }
         });
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
    }
    }

Upvotes: 1

Views: 666

Answers (1)

XtremeBaumer
XtremeBaumer

Reputation: 6435

The following code will work. Your first problem was that you get the selectedFile before the user could select anything (moved it down to where the user selected a file). Your next problem was the layout. As a starter you should begin with BorderLayout as its easy to handle until you get the concepts. The 3rd problem was that you added the TextArea 2 times. 1st time with jfrm.add(edit); and second time with jfrm.add(sta);. You only have to add the ScrollPane as it contains the TextArea.

package test;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileSystemView;

class Menu implements ActionListener {
    public Menu() {
        JFrame jfrm = new JFrame("Menudemo");
        jfrm.setLayout(new BorderLayout());
        jfrm.setSize(720, 700);

        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        JTextArea edit = new JTextArea("HI I AM A TEXTAREA");
        edit.setEditable(true);
        JScrollPane sta = new JScrollPane(edit);

        sta.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        sta.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        JMenuBar jmb = new JMenuBar();

        JMenu jmfile = new JMenu("File");
        JMenuItem jmiopen = new JMenuItem("Open");
        JMenuItem jmiclose = new JMenuItem("Close");
        JMenuItem jmisave = new JMenuItem("Save");
        JMenuItem jmiexit = new JMenuItem("Exit");
        jmfile.add(jmiopen);
        jmfile.add(jmiclose);
        jmfile.add(jmisave);
        jmfile.add(jmiexit);
        jmb.add(jmfile);

        // i want to open a file through the dialog box and load the content into the
        // text area
        jmiopen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                try {

                    int returnvalue = jfc.showOpenDialog(null);

                    if (returnvalue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = jfc.getSelectedFile();
                        try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
                            String line = reader.readLine();

                            while (line != null) {
                                edit.append(line);
                                line = reader.readLine();
                            }
                            //Suggestion opposed by Andrew Thompson; 
                            //would be used instead of while loop. 
                            //It will override any existing text 
                            //with the whole content of the file
                            edit.read(reader, selectedFile);

                        }
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        });
        jmiclose.addActionListener(this);
        jmisave.addActionListener(this);
        jmiexit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });

        jfrm.add(sta);
        jfrm.setJMenuBar(jmb);
        jfrm.setVisible(true);
        // jfrm.pack();

    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Menu();

            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
}

Upvotes: 1

Related Questions