oneat
oneat

Reputation: 10994

JTextArea getting whole line

How can I get chosen line from JTA ?

Upvotes: 1

Views: 3239

Answers (2)

Sean
Sean

Reputation: 7747

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);
 }
}

Upvotes: 1

KarlP
KarlP

Reputation: 5191

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.

Upvotes: 2

Related Questions