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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

TextArea 2

Status
Not open for further replies.

steve981

MIS
Apr 2, 2004
2
CA
If i have 5 lines in a TextArea, how can i access only the third line?, i searched a lot but the nearest thing i found is getText(), but that gives me all the text.
 
//If you use JTextare in Swing, you can select the third line
Code:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
class jt extends JFrame
      {
       public jt()
              {
               super("jt");
               JPanel p = new JPanel(new BorderLayout());
               JTextArea chatText = new JTextArea("one\ntwo\nthree",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);
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");}
              }
       public boolean isManagingFocus() // all your JComponents should have this method overidden like this if you want to manage focus yourself
              {
               return true;
              }
       public static void main(String args[])
              {
               jt jtObj = new jt();
               jtObj.setSize(400,400);
               jtObj.setVisible(true);
              }
      }
 
Or you could "getText()" the whole area and tokenize on "\n".

Bob Rashkin
rrashkin@csc.com
 
two "\n" are needed to identify three lines, so the default text in the JTextArea in my program code also needs to contain "\n".
If the width of the JTextArea is so small that the line number will seem to be greater.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top