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!