int caretPos = textArea.getCaretPosition();
if(caretPos>=0) {
AbstractDocument doc = (AbstractDocument)textArea.getDocument();
Element element = doc.getParagraphElement(caretPos);
System.out.println(Integer.toString(element.getParentElement().getElementIndex(element.getStartOffset())+1));
}
// Cursorposition holen
int caretPos = textArea.getCaretPosition();
// Wenn Cursor überhaupt drin
if(caretPos>=0) {
// Document des Texfeldes holen
AbstractDocument doc = (AbstractDocument)textArea.getDocument();
// Textelement an Cursorposition holen (in JTextarea ist i.d.R. 1 Element = 1 Zeile)
Element element = doc.getParagraphElement(caretPos);
// Im Übergeordneten Element prüfen, an welcher Stelle das gefundene sich befindet. Es ist dann gleich die Zeilennummer
System.out.println(Integer.toString(element.getParentElement().getElementIndex(element.getStartOffset())+1));
}
thE_29 hat gesagt.:JTextArea.getCaret().getMark() geht auch, schau was dir das zurückbringt!
thE_29 hat gesagt.:Achso, du willst die Zeilenanzahl, tjo, das ist ne gute Frage![]()
public static int getCaretRowPosition(JTextComponent comp) {
try {
int y = comp.modelToView(comp.getCaretPosition()).y;
int line = y/getRowHeight(comp);
return ++line;
} catch (BadLocationException e) {
}
return -1;
}
public static int getCaretColumnPosition(JTextComponent comp) {
int offset = comp.getCaretPosition();
int column;
try {
column = offset - Utilities.getRowStart(comp, offset);
} catch (BadLocationException e) {
column = -1;
}
return column;
}
Roar hat gesagt.:Code:public static int getCaretColumnPosition(JTextComponent comp) { int offset = comp.getCaretPosition(); int column; try { column = offset - Utilities.getRowStart(comp, offset); } catch (BadLocationException e) { column = -1; } return column; }
Roar hat gesagt.:Code:public static int getCaretRowPosition(JTextComponent comp) { try { int y = comp.modelToView(comp.getCaretPosition()).y; int line = y/getRowHeight(comp); return ++line; } catch (BadLocationException e) { } return -1; }
cannot find symbol
symbol : method getRowHeight(javax.swing.JTextArea)
int line = y/text.getRowHeight();
getRowHeight() has protected access in javax.swing.JTextArea