Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read line one by one from a JTextArea

Status
Not open for further replies.

proteome

Technical User
May 14, 2003
115
US
Is it possible to read strings from as JTextArea One by One?? I would like to insert all the lines from the JTextArea into a String Array for later usage.

Code:
String [] temp = new String[jtextarea.getLineCount();

for(int i = 0; i<=jtextarea.getLineCount();i++)
{
   temp[i] = something like jtextarea.getLine[i];
}
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
class jt extends JFrame implements ActionListener
{
JTextArea chatText;
JButton jb;
public jt()
{
super("jt");
jb = new JButton("click");
JPanel p = new JPanel(new BorderLayout());
chatText = new JTextArea("one\ntwo\nthreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"+
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",10, 30);
chatText.setLineWrap(true);
chatText.setEditable(true);
//chatText.setForeground(Color.white);
//chatText.setBackground(new Color(80,0,0));

JScrollPane chatTextPane = new JScrollPane();
chatTextPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER );
chatTextPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JViewport vp = chatTextPane.getViewport();
vp.add(chatText);
p.add(chatTextPane, BorderLayout.CENTER);
getContentPane().add(p,BorderLayout.CENTER);
getContentPane().add(jb,BorderLayout.SOUTH);
try {
System.out.println(chatText.getLineStartOffset(2));
System.out.println(chatText.getLineEndOffset(2));
System.out.println( (chatText.getText()).substring(chatText.getLineStartOffset(2),chatText.getLineEndOffset(2)) );
}
catch (BadLocationException be)
{System.out.println("invalid line no");}
jb.addActionListener(this);
}
public boolean isManagingFocus() // all your JComponents should have this method overidden like this if you want to manage focus yourself
{
return true;
}
public void actionPerformed(ActionEvent event)
{
try {
System.out.println(chatText.getLineStartOffset(2));
System.out.println(chatText.getLineEndOffset(2));
System.out.println( (chatText.getText()).substring(chatText.getLineStartOffset(2),chatText.getLineEndOffset(2)) ); // get third line by finding the second new line character
}
catch (BadLocationException be)
{System.out.println("invalid line no");}
}
public static void main(String args[])
{
jt jtObj = new jt();
jtObj.setSize(400,400);
jtObj.setVisible(true);
}
}
// you have to use \n or press enter in JTextArea to add a new line
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top