How can I get cho开发者_开发知识库sen line from JTA ?
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.
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);
}
}
精彩评论