#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0

    Reading .txt - place into jList - read \n


    Hi All,

    I wonder if someone could help me... I am trying to read a list of items from a .txt file line by line and place them into a jList.
    Once they are in the jList, I click on it to insert to a jTextArea.

    This is working apart from one thing. I have certain lines of text that I need to put onto a new line when they are selected from the jList and put into the jTextArea.

    Unfortunately, I cannot seem to get the reader to understand a newline character. Is this possible?

    Eg.
    .txt contains:

    Apple
    Orange
    Pineapple \n Grape
    Strawberry

    I would like to get the "\n" to add a new line when selected from the jList.

    Many Thanks in Advance,
    Matt
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    I cannot seem to get the reader to understand a newline character
    Can you post the code you are having problems with so it can be tested?

    What is in the .txt file between Apple and Orange, etc? The way it was posted makes it look like there is a newline character between them.
    Is the \n that is shown after Pineapple two characters in the file? a \ and an n?

    If they are two characters, the code could use some of the String class's methods to find them and replace them with a single newline character.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0

    My Code


    Thank you for your response:


    Code:
    package jlistfromtext;
    
    
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.swing.DefaultListModel;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    
    public class FORMTEST extends javax.swing.JFrame {
    
        class MyListSelectionListener implements ListSelectionListener {
        // This method is called each time the user changes the set of selected items
        public void valueChanged(ListSelectionEvent evt) {
            
            // When the user release the mouse button and completes the selection,
            // getValueIsAdjusting() becomes false
            if (!evt.getValueIsAdjusting()) {
                JList list = (JList)evt.getSource();
    
                // Get all selected items
                Object[] selected = list.getSelectedValues();
    
                // Iterate all selected items
                for (int i=0; i<selected.length; i++) {
                    Object sel = selected[i];
                                   
                   String str = (String) sel;
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
    		Clipboard clipboard = toolkit.getSystemClipboard();
    		StringSelection strSel = new StringSelection(str);
    		clipboard.setContents(strSel, null);
                    
                    
                    //System.out.print(str);
                    
                    String AlreadyHaveThis = jTextArea1.getText();
                    jTextArea1.setText(AlreadyHaveThis + str + "\n\n");
                }
                
            }
            
        }
        
        }
        
        /**
         * Creates new form FORMTEST
         */
        public FORMTEST() {
            initComponents();
            TESTLIST.addListSelectionListener(new MyListSelectionListener());
                          }
    
        
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jScrollPane1 = new javax.swing.JScrollPane();
            TESTLIST = new javax.swing.JList();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jScrollPane2 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton3 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jScrollPane1.setViewportView(TESTLIST);
    
            jButton1.setText("FRUIT LIST");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText("VEGETABLE LIST");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane2.setViewportView(jTextArea1);
    
            jButton3.setText("Clear");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(61, 61, 61)
                            .addComponent(jButton3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(35, 35, 35)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2)
                        .addComponent(jButton3))
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            File FRUIT = new File("C:...");
            BufferedReader MyReader = null;
            DefaultListModel FruitList = new DefaultListModel();
            JList jList1 = new JList();
            jList1.setModel(FruitList);
            
          
            try {
                MyReader = new BufferedReader(new FileReader(FRUIT));
                String textfromfile = null;
                                     
                                     
               while ((textfromfile = MyReader.readLine()) != null) {
                   
                                     
                    FruitList.addElement(textfromfile);
                    
                // Append the read line to the main form with a linefeed ('\n')
                
                //System.out.println(textfromfile);
                    
                  TESTLIST.setModel(FruitList);  
                  
                  
                }
                jList1.setModel(FruitList);
                
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (MyReader != null) {
                        MyReader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }                                        
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            File VEGETABLES = new File("C:....");
            BufferedReader MyReader2 = null;
            DefaultListModel VegetableList = new DefaultListModel();
            JList jList2 = new JList();
            jList2.setModel(VegetableList);
     
            try {
                MyReader2 = new BufferedReader(new FileReader(VEGETABLES));
                String textfromfile = null;
                            
                while ((textfromfile = MyReader2.readLine()) != null) {
                    
                  VegetableList.addElement(textfromfile);
                                   
                  TESTLIST.setModel(VegetableList); 
                  
                }
                jList2.setModel(VegetableList);
                
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (MyReader2 != null) {
                        MyReader2.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }                                        
    
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            jTextArea1.setText(" ");
        }                                        
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
             
           
           
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(FORMTEST.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(FORMTEST.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(FORMTEST.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(FORMTEST.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new FORMTEST().setVisible(true);
                                  }
            });
            
        }
        // Variables declaration - do not modify
        public static javax.swing.JList TESTLIST;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        public javax.swing.JTextArea jTextArea1;
        // End of variables declaration
    }
    The .txt files called "Fruit.txt" and "Vegetable.txt" contain the following:

    Apple \n Blueberry
    Orange
    Pineapple \n Grape
    Strawberry

    Carrot \n Cucumber
    Sprout
    Radish
    Turnip \n Parsnip[/FONT]
  6. #4
  7. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,631
    Rep Power
    1945
    Please use code tags, it will make the code easier to read.
    e.g.
    Code:
    // your code here
  8. #5
  9. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    To create a String with these two characters: \n you need to "escape" the \ so it is not used as the special character: "\\n"
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0
    Originally Posted by NormR
    To create a String with these two characters: \n you need to "escape" the \ so it is not used as the special character: "\\n"
    Please can you let me know how to upload a picture so as I can show what I am after?

    Many Thanks,
    Matt
  12. #7
  13. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    Did you look in the Go Advanced button? Could be you haven't been on the forum long enough.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0
    Originally Posted by NormR
    Did you look in the Go Advanced button? Could be you haven't been on the forum long enough.
    I don't seem to have that option. Is there anyway I can send you the jpeg. I think it would really help in understanding the issue?

    Many Thanks,
    Matt
  16. #9
  17. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    Is the issue that a String has the two characters: \n in it
    and you want to remove those two characters and insert a newline there?

    Look at the String class. It has methods for finding and replacing parts of a String.
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0
    Originally Posted by NormR
    Is the issue that a String has the two characters: \n in it
    and you want to remove those two characters and insert a newline there?

    Look at the String class. It has methods for finding and replacing parts of a String.
    Thank you. I have it working now.

    Needed a double escape:
    Code:
    str = str.replaceAll("\\\\n", "\n");

IMN logo majestic logo threadwatch logo seochat tools logo