Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Trying to display text from file in JTextArea. Please Help.

  1. #1
    Junior Member
    Join Date
    Feb 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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

    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. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Trying to display text from file in JTextArea. Please Help.

    See the following link for all the nitty gritty on File IO: Lesson: Basic I/O (The Java™ Tutorials > Essential Classes)
    For text files, see Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Classes > Basic I/O) , which gives some basic code for how to read a file line by line.

  3. #3
    Junior Member
    Join Date
    Feb 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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?

  4. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Cool Re: Trying to display text from file in JTextArea. Please Help.

    Try something like this:



    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.

  5. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Trying to display text from file in JTextArea. Please Help.

    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.

    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)

  6. #6
    Junior Member
    Join Date
    Feb 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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:

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

  7. #7
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default 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.

  8. #8
    Junior Member
    Join Date
    Jun 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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.
     
    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;
    	}

Similar Threads

  1. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  2. Display in a text area
    By susieferrari in forum Java Theory & Questions
    Replies: 21
    Last Post: March 22nd, 2011, 09:56 AM
  3. How can I avoid JTextArea from grabbing focus upon setting text
    By Orit in forum Java Theory & Questions
    Replies: 4
    Last Post: October 4th, 2010, 05:17 AM
  4. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  5. How can I append text in JTextArea from another class
    By chikaman in forum AWT / Java Swing
    Replies: 2
    Last Post: December 10th, 2009, 10:26 AM

Tags for this Thread