Trying to display text from file in JTextArea. Please Help.
I'm trying to display some text in a JTextArea I have set up in a simple GUI. Easy right? That's what I thought, but I'm clearly not that advanced at Java. The hook is the information I want to display in the JTextArea is in a text file (file.txt).
Right now I have a main class and a class called TextArea that houses the GUI and two methods. In the main class I have set up a simple array with some text in it, and I'm able to get it to display in the JTextArea. Basically the code all works fine, the only thing I can't figure out and need to change is have the information in the array coming from a text file. So if anyone can help me figure this out I'd really appreciate it.
Here's my code for the Main class
Code Java:
package texttoarraylist;
import java.util.*;
import java.io.*;
/**
*
* @author RJ
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String dvds [] = {"text1", "text2"};
ArrayList myList = new ArrayList();
for (int sub = 0; sub < dvds.length; sub++){
myList.add(dvds[sub]);
}
TextArea one = new TextArea();
one.setVisible(true);
one.setShowText(myList);
}
}
And here's the code for the TextArea Class
Code Java:
package texttoarraylist;
/**
*
* @author RJ
*/
public class TextArea extends javax.swing.JFrame {
/** Creates new form TextArea */
public TextArea() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textArea.setColumns(20);
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setRows(5);
jScrollPane1.setViewportView(textArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(108, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private java.util.ArrayList getShowText(){
//go to tShow and get its text, put it into one string
String dvd = textArea.getText();
java.util.ArrayList myList = new java.util.ArrayList();
java.util.StringTokenizer one = new java.util.StringTokenizer(dvd, "\n");
while(one.hasMoreElements()){
myList.add(one.nextToken());
}
return myList;
}
public void setShowText(java.util.ArrayList myList){
String show = new String();
for (int sub = 0; sub < myList.size(); sub++)
show += myList.get(sub) + "\n";
textArea.setText(show);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TextArea().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea textArea;
// End of variables declaration
}
Re: Trying to display text from file in JTextArea. Please Help.
Re: Trying to display text from file in JTextArea. Please Help.
Isn't there some quick solution to this though? Like, I think I'm only missing a little piece of the code. Can't you do some version of:
String dvds [] = new BufferedReader(fileName("file.txt"));
This is obviously not working, but isn't there something like that that can just take a text file and throw it into an ArrayList, or an Array and then the Array into an ArrayList?
Re: Trying to display text from file in JTextArea. Please Help.
Try something like this:
Code java:
JTextArea area = new JTextArea(30,30);
String str = "";
Scanner reader = new Scanner("File.txt");
while (reader.hasNext())
{
str = str + reader.nextLine();
}
area.setText(str);
I'm not sure what the array does.
Are you storing each line as an index in the array?
Also, ArrayList is generic.
ArrayList<String> list = new ArrayList<String>();
list.add("some words");
// the above is how to add to an ArrayList.
You could add it using the loop I showed above.
As for your question in your last post, the answer is a no.
A String array cannot be initialized to a BufferReader object, which is what that's doing.
In fact, you can't even initialize just a plain old String to that either.
You need to use a Scanner in any event.
Re: Trying to display text from file in JTextArea. Please Help.
Quote:
You need to use a Scanner in any event.
No you don't need to use Scanner. In fact, a BufferedReader is just that: buffered (aka faster). And if you are doing string addition, recommend you use a StringBuffer or StringBuilder.
Quote:
String dvds [] = new BufferedReader(fileName("file.txt"));
You cannot assign variables like that...you must loop through the file and read it. That link I provided above shows some simple code for how to do this, as does javapenguin's code above (although I recommend against using String addition and recommend using a BufferedReader)
Re: Trying to display text from file in JTextArea. Please Help.
I've pretty much figured out all of the major issues I was having trouble with, thanks to the help from the people in these forums(thanks!). The info from my text file is displaying in the JTextArea but for some reason I can only get the last line of the file to display. There are 10 lines in the text file that I'm trying to display.
Here's my updated code:
Code :
public TextArea() {
initComponents();
try {
FileReader one = new FileReader ("info.txt");
BufferedReader buf = new BufferedReader(one);
String line = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//textArea.setText(line);
while ((line = buf.readLine()) != null) {
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
//reset token number
tokenNumber = 0;
//textArea.setText(line);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File not found");
} catch (IOException e){
JOptionPane.showMessageDialog(this, "Data not read");
}
Re: Trying to display text from file in JTextArea. Please Help.
The JTextArea.setText(..) method replaces the text. To append text to it, use the JTextArea.append(..) method.
Re: Trying to display text from file in JTextArea. Please Help.
Hi,
i have the same problem. I trying to display a text in JTextArea.
@rjdelight : Did you find a solution?
@All: or Here is my code. If somebody has an idea.
Code :
private String string;
public MyDocument() {
try {
int offset = 0;
int x = 0;
for (int i = 0; i < 1024; i++) {
string = UUID.randomUUID().toString() + "\n";
if ((string != null) && (x < 10)) {
x++;
}
insertString(offset, string, null);
offset += string.length();
}
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String getText(int offset, int length) throws BadLocationException {
System.out.println(String.format("getText: Offset %d / Length: %d",
offset, length));
return super.getText(offset, length);
}
@Override
public void getText(int offset, int length, Segment seg)
throws BadLocationException {
System.out.println(String.format(
"getTextWithSegment: Offset %d / Length: %d", offset, length));
super.getText(offset, length, seg);
}
@Override
public int getLength() {
int length = super.getLength();
System.out.println("getLength: " + length);
return length;
}