Jump to content

Text File to ArrayList for JTextArea??

- - - - -

  • Please log in to reply
3 replies to this topic

#1
rjdelight

rjdelight

    Newbie

  • Members
  • Pip
  • 4 posts
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


}



#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Something like:


File file = new File("C:\\someFolder\\otherFolder\\file.txt");

Scanner scanner = new Scanner(file);

List<String> lines = new ArrayList<String>();


while(scanner.hasNextLine()){

  lines.add(scanner.nextLine());

}


one.setShowText(lines);



#3
rjdelight

rjdelight

    Newbie

  • Members
  • Pip
  • 4 posts
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");

        }




#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Every time you set the text of the textarea, try to append it like so:

textArea.setText(textArea.getText() + line);






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users