Question

I have a program and am trying to test to see if a file (info.txt) is created and if it is, open the contents into a JTextArea as the program starts up. How would i go about doing this? ive already figured out how to search and see if the file exists, just can not get it to open into the textArea on startup

import javax.swing.*; // need it
import java.awt.*;   //need it also
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*; //keeps track of events
import javax.swing.border.*; // not necessary / already imported ^^

import javax.swing.*; 
import java.awt.*;   
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*; 
import javax.swing.border.*;

public class finalA extends JFrame implements ActionListener{
 private final int WIDTH = 750;
 private final int HEIGHT = 400;
 static String theText;
 private String text;

 //creates components
 private JTextArea textArea;
 private JButton SaveB;
 private JScrollPane scroll;


 public finalA(){
 setTitle("Super fancy text editor");
 setSize(WIDTH,HEIGHT);

  Container pane = getContentPane();

  //Creates button
  SaveB = new JButton("Save & Exit");
  textArea = new JTextArea();
  scroll = new JScrollPane(textArea);
  scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

  //adds event handler for exit button

  SaveB.addActionListener(this);

  //sets pane to null
  pane.setLayout(null);

  //location of button and TA (750,400)
  textArea.setLocation(10,100);
  SaveB.setLocation(150,320);

  //set size of TA and Button
  textArea.setSize(730,200);
  SaveB.setSize(100,30);

  //add items to pane
  pane.add(textArea);
  pane.add(SaveB);

  scroll.setBounds(10,100,730,200);
  scroll.setVisible(true);

  textArea.setLineWrap(true);
  textArea.setWrapStyleWord(true);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  }//ends constructor

  public void openFile()throws Exception{
   File f = new File("info.txt");
   if(f.exists()){
    FileReader reader = null;
    try{
     reader = new FileReader("info.txt");
     textArea.read(reader, null);
    } 
    finally{
     if (reader != null){
        reader.close();
     }
    }
   }
  }//ends openFile

  public void actionPerformed(ActionEvent e){
   String text = textArea.getText();
   if(e.getActionCommand().equals("Save & Exit")){

    try{
     BufferedWriter reader = new BufferedWriter(new FileWriter(new File("info.txt"),true));
     reader.write(text);
     reader.newLine();
     reader.close();
    }catch(IOException E){
    System.out.println("the error is " + E);
    }
   }
   System.exit(0);



 } 
}// ends finalA class
Was it helpful?

Solution

So, based on your available code you should simply need to call openFile at the end of your constructor, after you've created the JTextArea

public TestRead() {
    //...
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    try {
        openFile();
    } catch (IOException exp) {
        exp.printStackTrace();
    }
}//ends constructor

Don't use null layouts, pixel perfect layouts are an illusion in modern GUI design. You don't control factors like font metrics, DPI or rendering pipelines all of which can change the individual requirements of components.

Swing has been designed to make use layout managers and much of the functionality that updates the interface is related to it. If you do away with the layout manager, be ready of a load of never ending work and frustration

OTHER TIPS

Load file by using a file reader stream ,such as Scanner ,then append text to the textarea.

Here is a simple demo:

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.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
* simple demo to load file to textarea
*/
public class FileLoaderTest {
    public static void main(String[] args) throws IOException{
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                JFrame frame = new JFrame("Load File Demo");
                JPanel panel = new JPanel();
                JButton btnLoad = new JButton("Load File");
                final JTextArea textArea = new JTextArea(10,20);
                btnLoad.addActionListener(new ActionListener(){

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        JFileChooser fileChooser = new JFileChooser();
                        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
                        fileChooser.setFileFilter(new FileNameExtensionFilter
                                  ("Text File", "txt"));
                        fileChooser.setAcceptAllFileFilterUsed(false);
                        while(true)
                        {
                            if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ) {

                                if(!fileChooser.getSelectedFile().exists()) {
                                    JOptionPane.showMessageDialog(fileChooser, 
                                            "You must select an existing file!","open File",
                                            JOptionPane.ERROR_MESSAGE);//continue
                                }else {
                                    //read file to the textArea
                                    File file = fileChooser.getSelectedFile();
                                    try {
                                        Scanner scanner = new Scanner(new  BufferedReader
                                                   (new FileReader( file)));
                                         while(scanner.hasNext()) {
                                             textArea.append(scanner.nextLine()+"\n");
                                          }
                                         scanner.close();
                                    } catch (FileNotFoundException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }
                                    break;//successfully open break
                                }
                            }else {
                                break;//user cancel open break
                            }
                        }
                    }
                });
                JScrollPane scrollPane = new JScrollPane(textArea);
                panel.add(btnLoad);
                frame.add(panel,BorderLayout.NORTH);
                frame.add(scrollPane,BorderLayout.CENTER);
                frame.setSize(400, 400);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

From your question I assume you have gotten this far:

BufferedReader in = null;
    try{
        in = new BufferedReader(new FileReader("C:\\path\\to\\file\\info.txt"));
        String str = in.readLine();
        ArrayList<String> textList = new ArrayList<String>();
        while((str = in.readLine()) != null){
            textList.add(str); //saves each line that is read from the file
        }

        //-->This is where you will add later code

    }catch(IOException e){
        System.out.println("Error reading file");
        e.printStackTrace();
    }

From here you should use the

JTextArea.append()
method like so:

--Insert after the while loop in the readFile() method.

for(String s:textList){
    yourJTextArea.append(s +"\n");
}

A full example:

import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JTextArea;


public class TextRead extends JFrame{

    static JTextArea mytextArea;

    public TextRead(){
        super("TextRead");

        mytextArea = new JTextArea();
        mytextArea.setPreferredSize(new Dimension(500,500));

        getContentPane().add(mytextArea);

        setContentPane(getContentPane());

        pack();
        setVisible(true);
        setSize(500,500);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        readFile();
    }

    private void readFile() {
        BufferedReader in = null;
        try{
            String path = "C:\\Users\\steve_000\\Desktop\\info.txt"; //<--your path goes  here!
            in = new BufferedReader(new FileReader(path));
            String str = in.readLine();
            ArrayList<String> textList = new ArrayList<String>();
            while((str = in.readLine()) != null){
                textList.add(str); //saves each line that is read from the file
            }

            for(String s: textList){
                mytextArea.append(s + "\n"); //prints each line consecutively
            }

        }catch(IOException e){
            System.out.println("Error reading file");
            e.printStackTrace();
        }
    }

    public static void main(String... args){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                runGUI();
            }
        });
    }

    public static void runGUI() {
        TextRead tr = new TextRead();
        JFrame.setDefaultLookAndFeelDecorated(false);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top