Java Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesJava Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old September 17th, 2012, 11:05 AM
SnakeySnakey87 SnakeySnakey87 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2012
Posts: 5 SnakeySnakey87 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 7 sec
Reputation 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

Reply With Quote
  #2  
Old September 17th, 2012, 11:35 AM
NormR's Avatar
NormR NormR is offline
Contributing User
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Aug 2010
Location: SW Missouri
Posts: 2,955 NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 53 m 34 sec
Reputation Power: 345
Quote:
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.

Reply With Quote
  #3  
Old September 18th, 2012, 05:40 AM
SnakeySnakey87 SnakeySnakey87 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2012
Posts: 5 SnakeySnakey87 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 7 sec
Reputation 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]

Reply With Quote
  #4  
Old September 18th, 2012, 06:05 AM
MrFujin's Avatar
MrFujin MrFujin is offline
Lord of the Dance
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Oct 2003
Posts: 3,129 MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level)MrFujin User rank is General 11st Grade (Above 100000 Reputation Level) 
Time spent in forums: 2 Months 2 Weeks 22 h 57 m 20 sec
Reputation Power: 1736
Please use code tags, it will make the code easier to read.
e.g.
Code:
// your code here

Reply With Quote
  #5  
Old September 18th, 2012, 07:01 AM
NormR's Avatar
NormR NormR is offline
Contributing User
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Aug 2010
Location: SW Missouri
Posts: 2,955 NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 53 m 34 sec
Reputation Power: 345
To create a String with these two characters: \n you need to "escape" the \ so it is not used as the special character: "\\n"

Reply With Quote
  #6  
Old September 18th, 2012, 08:09 AM
SnakeySnakey87 SnakeySnakey87 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2012
Posts: 5 SnakeySnakey87 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 7 sec
Reputation Power: 0
Quote:
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

Reply With Quote
  #7  
Old September 18th, 2012, 09:02 AM
NormR's Avatar
NormR NormR is offline
Contributing User
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Aug 2010
Location: SW Missouri
Posts: 2,955 NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 53 m 34 sec
Reputation Power: 345
Did you look in the Go Advanced button? Could be you haven't been on the forum long enough.

Reply With Quote
  #8  
Old September 18th, 2012, 09:10 AM
SnakeySnakey87 SnakeySnakey87 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2012
Posts: 5 SnakeySnakey87 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 7 sec
Reputation Power: 0
Quote:
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

Reply With Quote
  #9  
Old September 18th, 2012, 09:18 AM
NormR's Avatar
NormR NormR is offline
Contributing User
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Aug 2010
Location: SW Missouri
Posts: 2,955 NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 53 m 34 sec
Reputation Power: 345
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.

Reply With Quote
  #10  
Old September 18th, 2012, 09:34 AM
SnakeySnakey87 SnakeySnakey87 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2012
Posts: 5 SnakeySnakey87 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 7 sec
Reputation Power: 0
Quote:
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");

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesJava Help > Reading .txt - place into jList - read \n

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap