views:

26

answers:

2

How can I get chosen line from JTA ?

+2  A: 

I suppose you can use getLineStartOffset(int line), and getLineEndOffset(int line) to substring out a particular line from the string returned from getText()

If you mean that you want to know what the user has selected (using the mouse/keyboard): getSelectedText() should give you that.

KarlP
+1, for the more efficient solution that is taken directly from the JTextArea API.
camickr
A: 

Why not break the lines up into tokens. then if you know the line number you want, you can just access it via an array of Strings

public class JTALineNum extends JFrame{
 JTextArea jta = null;
 JButton button = null;

 public JTALineNum(){
  jta = new JTextArea();
  button = new JButton("Hit Me");

  button.addActionListener(new ButtonListener());

  add(jta, BorderLayout.CENTER);
  add(button, BorderLayout.SOUTH);
  setSize(200,200);
  setVisible(true);
 }

 private class ButtonListener implements ActionListener{

  public void actionPerformed(ActionEvent e) {
   String text = jta.getText();
   String[] tokens = text.split("\n");
   for(String i : tokens){
    System.out.println("Token:: " + i);
   }
  }
 }

 public static void main(String args[]){
  JTALineNum app = new JTALineNum();
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}
Sean