Hi all! I am having some trouble displaying the whole of a file within a JTextArea.
The problem is that every new line of code that's read is showing within its own JTextArea rather than the text being displayed within a single JTextArea.

I assume that the problem is something to do with either the BufferedReader method readLine() or the way I have set up my JTextArea.

Any help would be much appreciated, I've spent quiet a few hours trying to figure this out and it's proven to be a huge pain.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class MovieList {

	public static void openFile() {		
		try{
			JFileChooser fileChooser = new JFileChooser(".");
			fileChooser.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Opening File");
				}
			});

			int status = fileChooser.showOpenDialog(null);

			if (status == JFileChooser.APPROVE_OPTION) {
				File selectedFile = fileChooser.getSelectedFile();
				System.out.println(selectedFile.getParent());
				System.out.println(selectedFile.getName());
				File f = fileChooser.getSelectedFile();
				BufferedReader br = new BufferedReader(new FileReader(f));
				String st="";
				while((st = br.readLine()) != null) {
					displayText(st);
					System.out.println(st);
				}
			} else if (status == JFileChooser.CANCEL_OPTION)
				JOptionPane.showMessageDialog(null, "Canceled");
			// Catches any error conditions
		} catch (IOException e){
			System.err.println("Unable to open file");
			System.exit(0);
		}
	}


	public static void displayText(String s) {
		JFrame frame = new JFrame();
		JTextArea ta = new JTextArea(500, 500);

		frame.getContentPane().add(BorderLayout.CENTER, ta);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300,300);
		frame.setVisible(true);
		ta.append(s);
	}	


 public static void main(String[] args) {
		 openFile();
	 }
}

Thanks in advance!

Recommended Answers

All 3 Replies

In your method displayText(String s) you construct a JFrame and JTextArea for every call you make to it, which is for ever line you read.

You should only construct these once, and hold the text you want to show in the textArea in a variable and just call textArea.setText(theText).

Every time you read a line you call displayText, in which you create and add a new TextArea.
You should create the frame etc with a single text area when the application starts, and just add the String to that existing text area in displayText.

Thank so much SasseMan and JamesCherrill I really appreciate your help.

I've corrected my code and its working perfectly now!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.