levijoraan levijoraan - 5 months ago 9
Java Question

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.

Answer

You need to create an object of the class which contains the variable resultBox. Now access the variable resultBox using the reference variable of the object of the class. For example if class name is Test, then:

Test test=new Test( );

test.resultBox.read ( br, null );

Could you please follow steps mentioned below and see the results:

Step 1: Create a text file whose path is : "D:\\test.txt"

Step 2: Replace your public static void main(String args[]) with the following:

public static void main(String[] args) throws IOException {     
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                RemoteDesktop rd=new RemoteDesktop();
                FileReader fr=null;
                try {
                    fr = new FileReader("D:\\test.txt");
                    rd.resultBox.read(fr, "Test");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    if(fr!=null){
                        try {
                            fr.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                rd.setSize(600,  400);
                rd.setLocationRelativeTo(null);
                rd.setVisible(true);
            }
        });
    }
Comments