The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Java Help
|
Reading .txt - place into jList - read \n
Discuss Reading .txt - place into jList - read \n in the Java Help forum on Dev Shed. Reading .txt - place into jList - read \n Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

September 17th, 2012, 11:05 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
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

|

September 17th, 2012, 11:35 AM
|
 |
Contributing User
|
|
Join Date: Aug 2010
Location: SW Missouri
|
|
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.
|

September 18th, 2012, 05:40 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
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]
|

September 18th, 2012, 06:05 AM
|
 |
Lord of the Dance
|
|
|
|
Please use code tags, it will make the code easier to read.
e.g.
|

September 18th, 2012, 07:01 AM
|
 |
Contributing User
|
|
Join Date: Aug 2010
Location: SW Missouri
|
|
|
To create a String with these two characters: \n you need to "escape" the \ so it is not used as the special character: "\\n"
|

September 18th, 2012, 08:09 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
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 
|

September 18th, 2012, 09:02 AM
|
 |
Contributing User
|
|
Join Date: Aug 2010
Location: SW Missouri
|
|
|
Did you look in the Go Advanced button? Could be you haven't been on the forum long enough.
|

September 18th, 2012, 09:10 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
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 
|

September 18th, 2012, 09:18 AM
|
 |
Contributing User
|
|
Join Date: Aug 2010
Location: SW Missouri
|
|
|
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.
|

September 18th, 2012, 09:34 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
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");
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|