全部取出来,使用StringTokenizer进行分割,使用回车作为分割符

解决方案 »

  1.   

    try{
          //第一行
          String line1=jTextArea1.getText(0,jTextArea1.getLineEndOffset(0));
          //第二行
          String line2=jTextArea1.getText(jTextArea1.getLineEndOffset(0),jTextArea1.getLineEndOffset(1)-jTextArea1.getLineEndOffset(0));
        }catch(BadLocationException ex){
          System.out.println("行数不够...");
        }
      

  2.   

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;public class TextAreaTest extends Frame{
    TextArea ta;
    Button btn;
    Button btn2;
    Panel p;
    public TextAreaTest(){
    super("Text Area Test");
    ta=new TextArea(10,20);
    add(ta);
    btn=new Button("get first line");
    //the simplest implementation to get the first line
    btn.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent ev){
    String content=ta.getText();
    int pos=content.indexOf("\n");
    String fLine=null;
    if(pos<0){
    fLine=content.substring(0,pos);
    }else{
    fLine=content;
    }
    System.out.print(fLine);
    }
    }
    );
    btn2=new Button("get random line");
    //implementation for getting the random line content
    btn2.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent ev){
    Vector v=new Vector();
    String content=ta.getText();
    StringTokenizer tk=new StringTokenizer(content,"\n");
    while(tk.hasMoreTokens()){
    v.add(tk.nextToken());
    } //only an example here
    if(v.size()>1){
    System.out.println("get the 2nd Line: " + v.elementAt(1));
    }
    }
    }
    );
    p=new Panel();
    p.add(btn);
    p.add(btn2);
    add(p,BorderLayout.SOUTH);
    setVisible(true);
    pack();
    }
    public static void main(String[] args){
    TextAreaTest t=new TextAreaTest();
    }
    }