participate


Swing - JTextArea, inserting text at end of line
This question is answered. Correct Answer available

<<   Back to Forum  |   Give us Feedback
This topic has 6 replies on 1 page.
Joerg22
Posts:1,109
Registered: 6/25/03
JTextArea, inserting text at end of line   
Jan 29, 2008 3:18 AM
 
 
Hello,

on an XP platform I display a file's text in a JTextArea. The API clearly says under DefaultEditorKit that line ends are handled as \n. But it also says that the EndOfLineStringProperty takes care for platform differences. My example code below shows that when text is inserted at a line end, it goes right in between the CR and the LF which gives funny results when the textarea's contents is written back to a file.
Is this intended behavior of the textArea? And what is the recommended way to display and write files with CR+LF line terminators?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class InsertAtLineEnd
{ 
  public static void main(String args[])
  {
    JFrame frame = new JFrame("InsertAtLineEnd");
    frame.setSize(350, 300);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Container cp= frame.getContentPane();
    cp.setLayout(null);
    final JTextArea ta= new JTextArea();
    ta.setBounds(40,40,250,110);
    ta.setFont(new Font("Monospaced", Font.PLAIN, 12));
    ta.setText("   These are some sample lines\r\n"+
	"as read from a file on a windows\r\n"+
	"platform.\r\n   Place the cursor at any line\r\n"+
	"end and insert one or more\r\n"+
	"characters. Then press the button.\r\n");
    JButton b= new JButton("Get text");
    b.setBounds(105,200,80,30);
    b.setMargin(new Insets(0,0,0,0));
    b.addActionListener(new ActionListener()
    { public void actionPerformed(ActionEvent e)
      { String s=ta.getText();
	System.out.println(s);
	for (int i=0; i<s.length(); i++) {
	  System.out.println(s.charAt(i)+" "+(int)s.charAt(i));
	}
      }
    });
    cp.add(ta);
    cp.add(b);
    frame.setVisible(true);
  }
}
 
uncle_alice
Posts:3,813
Registered: 9/26/00
Re: JTextArea, inserting text at end of line   
Jan 29, 2008 4:46 AM (reply 1 of 6)  (In reply to original post )
Helpful
 
When you use the EditorKit's read() method to read text from a file and store it in the JTextArea, it converts any DOS "\r\n" or Mac "\r" line separators to "\n". The same thing happens when you use the built-in Paste command to paste text from the clipboard. But text you insert using the setText() or append() commands, or Document's insertString() or replace() methods, doesn't get filtered like that. The idea is that you just use "\n", and don't worry about what kind of line separators the file really uses.
 
Joerg22
Posts:1,109
Registered: 6/25/03
Re: JTextArea, inserting text at end of line   
Jan 29, 2008 5:22 AM (reply 2 of 6)  (In reply to #1 )
 
 
Hello Alice,

thank you for your reply. So we can say: Displaying files with CR+LF line terminators looks fine. Even modifiying the text in the middle or at beginning of a line is no problem when writing the text back to a file. But in case of modification at a line end, terminators have to be replaced.

Thanks again

J?rg
 
camickr
Posts:32,719
Registered: 2/27/98
Re: JTextArea, inserting text at end of line   
Jan 29, 2008 8:30 AM (reply 3 of 6)  (In reply to #2 )
 
 
The Document uses "\n" to represent the new line character.

When using the read() method the external new line string ("\r\n", "\n", "\r"), depending on the file being read, will be saved and will be converted to a "\n" when added to the Document.

When using the write(...) method the "\n" string will be converted back to the external new line string.

That is why it is always better to use the read() and write() methods of JTextComponent, than it is to create your own BufferedReader and BufferedWriter to read and write files. When using the latter approach you lose the original new line string information.
 
Joerg22
Posts:1,109
Registered: 6/25/03
Re: JTextArea, inserting text at end of line   
Jan 29, 2008 11:28 AM (reply 4 of 6)  (In reply to #3 )
 
 
Thanks for your explanation. My problem is only that I sometimes need to append a file to the textArea and read() can fill the area only from scratch. So at least in that case I have to do the conversion myself. With write(), however, there is no problem.
 
camickr
Posts:32,719
Registered: 2/27/98
Re: JTextArea, inserting text at end of line   
Jan 29, 2008 1:55 PM (reply 5 of 6)  (In reply to #4 )
Correct
 
sometimes need to append a file to the textArea

I have never tried it, but the DefaultEditorKit has a read(...) method that allows you to specify the insertion point into the Document. I assume it would parse out the new lines strings the same as the original read() method would.
 
Joerg22
Posts:1,109
Registered: 6/25/03
Re: JTextArea, inserting text at end of line   
Jan 31, 2008 3:26 AM (reply 6 of 6)  (In reply to #5 )
 
 
Yes, that works. Thank you.
/*
Reads one or several files to a JTextArea and optionally writes the contents of
the textarea back to a file. The read() and write() methods are used which take
care for platform dependent line terminators.
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
 
public class ReadFile extends JFrame {
  JTextArea ta;
  String filspc;
 
  public ReadFile() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(600, 400);
    Container cp= getContentPane();
    cp.setLayout(new BorderLayout());
    ta= new JTextArea();
    ta.setFont(new Font("Monospaced", Font.PLAIN, 12));
    JScrollPane scrollPane = new JScrollPane(ta);
    JButton bWrite= new JButton("Write file");
    bWrite.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
	filspc= getFilspc("Enter output file specification", "TestFileOut.txt",
									false);
	try {
	  BufferedWriter out= new BufferedWriter(new FileWriter(filspc));
	  ta.write(out);
	}
	catch (IOException e) {
	  System.out.println(e);
	  System.exit(0);
	}
      }
    });
    cp.add(BorderLayout.CENTER, scrollPane);
    cp.add(BorderLayout.SOUTH, bWrite);
    setVisible(true);
    filspc= getFilspc("Enter file specification", "TestFile.txt", true);
    try {
      BufferedReader in= new BufferedReader(new FileReader(filspc));
      ta.read(in, null);
    }
    catch (IOException e) {
      System.out.println(e);
      System.exit(0);
    }
 
    filspc= getFilspc("Enter file to append", "TestFile2.txt", true);
    try {
      DefaultEditorKit dek= new DefaultEditorKit();
      BufferedInputStream in= new BufferedInputStream(new FileInputStream
								(filspc));
      Document doc= ta.getDocument();
      dek.read(in, doc, doc.getLength());
    }
    catch (Exception e) {
      System.out.println(e);
      System.exit(0);
    }
  }
 
 
  public String getFilspc(String prompt, String iniString, boolean mustExist) {
    String s= new File(iniString).getAbsolutePath();
    s= JOptionPane.showInputDialog(this, prompt, s);
    if (s==null) System.exit(0);
    if (mustExist) {
      while (!new File(s).exists()) {
	JOptionPane.showMessageDialog(this, "File not found.",
		"Input file does not exist.", JOptionPane.ERROR_MESSAGE);
	s= getFilspc(prompt, iniString, true);
      }
    }
    return s;
  }
 
 
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
	new ReadFile();
      }
    });
  }
 
}
 
This topic has 6 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 59
  • Guests : 136

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums