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

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

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

}

You've already posted this and you really should figure out the GUI code for yourself instead of using Netbeans automatic thing.

It's hard to read your code with all of Netbeans' weird jumbled up mess of stuff

I'm sorry about the netbeans code, but I'm a beginner and using the built in GUI editor is effective for me at the present time. My two methods are directly under this part of the code

}// </editor-fold>

They're called getShowText and myList.

Well for such a simple program, you have way too much going on in here. I'm not going to do it for you, but I'll try to organize a bit into small readable code..

import java.awt.*;
import javax.swing.*;


public class Main {

	String text="";
	
    public static void main(String[] args) {
        
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocation(400, 200);
		frame.setSize(300, 300);
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setLayout(new GridLayout());
		
		JTextArea textarea = new JTextArea();
		frame.add(textarea);
    }
    public String getText(){
    	//code for openning file, scanning, and putting into String text
    	return text;
    }
}

This is just very basic GUI, but I'm going to leave the file openning, scanning, etc. for you to figure out (but I already answered this as well in the last post).

there are lots of mistakes

then

import java.awt.*;
import javax.swing.*;

public class Main {

    private String text = "";

    public static void main(String[] args) {
        JTextArea textarea = new JTextArea();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(textarea, BorderLayout.CENTER);
        frame.setResizable(false);
        frame.setLocation(400, 200);
        frame.setPreferredSize(new Dimension(300, 300));
        frame.pack();
        frame.setVisible(true);
    }

    public String getText() {
        //code for openning file, scanning, and putting into String text
        return text;
    }
}

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:

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");
        }

You need to save line to another string.

string += line; //replace with textArea.setText(line) is

put textArea.setText(string); outside of the loop

"\r\n" instead of "\n" for Windows OS

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.