I am developing a small editor applet using JTextare with line numbers . I created a panel with JTextArea for displaying line numbers. For showing line numbers i addded document listener to the Text area and appending the line number.(I am attaching the code below). Its working fine when i the wrap mode is off, but when i set the wrap mode on, i have problem in dispalying the line numbers... My main doubt is .. How can we get the position of cursor in the text area I want to know the line number where the cursor is located.
//editpanel is the textarea for Editing //linepanel is the textarea for line numbers //Adding document listener
editPanel.getDocument().addDocumentListener( new DocumentListener() { public void insertUpdate(DocumentEvent e) { int i=lineNum; for(;i<editPanel.getLineCount();i++) { linePanel.append(String.valueOf(i+1)+"."+"\n"); lineNum++; } save.setEnabled(true); //enable the save button if content is changed }
public void removeUpdate(DocumentEvent e) { save.setEnabled(true); //enable the save button if content is changed linePanel.setText(""); for(int i=0;i<editPanel.getLineCount();i++)linePanel.append(String.valueOf(i+1)+"."+ "\n"); lineNum=editPanel.getLineCount(); }
public void changedUpdate(DocumentEvent e) { save.setEnabled(true);//enable the save button if content is changed }
});
The above code works well if wrap mode is off, but when we switch the wrap mode on .. this is not working.
I dunno how far you want to go with that but ... Isn't the JEditorPane more appropriate for that ? When doing complex things, you may have to write your own "Document".
Look in the API's for : javax.swing.text.Document It is an interface.