Search code examples
javatextjtextarea

Set textArea of a JFrame to data from a file?


As the question states, I have a text file. Inside that text file is a few lines of text, and I want to populate my textArea with that data when the JFrame launches.

 public static void main(String args[]) throws IOException {

    FileReader reader = new FileReader("C:/filepathchangedforStackOverflow");
    BufferedReader br = new BufferedReader(reader);
    resultBox.read( br, null );
    br.close();

      java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RemoteDesktop().setVisible(true);

            }
        });
    }

The error is on resultBox.read( br, null ); as it is saying that non-static variable resultBox cannot be referenced from a static context.

I have looked everywhere and am not finding anything. It seems simple enough, I don't know why it's not working.


Solution

  • Try this:

    class Main

    {

    static JFrame frame=new JFrame(); 
    static JPanel panel=new JPanel();
    private static void display(JFrame frame) throws IOException 
        {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(null); 
            File file = null;
            if(returnVal == JFileChooser.APPROVE_OPTION)     
            file = chooser.getSelectedFile();    
            JTextArea text = new JTextArea();
            BufferedReader in = new BufferedReader(new FileReader(file));
            String line = in.readLine();
            while(line != null)
                {
                    text.append(line + "\n");
                    line = in.readLine();
                }
            panel.add(text);
            frame.add(panel);
        }
    public static void main(String args[]) throws IOException
    {
        frame. setTitle("Simple example");
        frame.setSize(500, 500);
        display(frame);
        frame.setVisible(true);
    }
    

    }