hi i'm trying to make a method to get the exact position of the caret in a JTextComponent similar as the getMagicCaretPosition(), but when I type only newline the method gettext(); doesn't get all the newlines that I have in my component
when i used to use getMagicCaretPosition() and also a ChangeListener, it doesn't work as well when i move the caret to the bottom or top in a empty newline, that's the reason now i'm trying to make my own method
this my CaretListener:
if(OBJETO instanceof JTextComponent){
JTextComponent objetotexto=(JTextComponent)OBJETO;
objetotexto.addCaretListener(new CaretListener() {
int pointx=0,pointy=0;
@Override
public void caretUpdate(CaretEvent e) {
JTextComponent tempo=((JTextComponent)e.getSource());
if(tempo.getCaret().getMagicCaretPosition()!=null){
//here replace the "\n" for ".__._..__:.__..-_...-__." because
//when i made the split the "\n" was lost
String aaaa=tempo.getText().substring(0, tempo.getCaret().getDot()).replaceAll("\n", ".__._..__:.__..-_...-__.");
System.out.println(aaaa.split(".__._..__:.__..-_...-__.").length+" must be the conut of newlines");
String te[]=aaaa.split("\\p{Space}");
for (int i = 0; i < te.length; i++) {
te[i]+=" ";
}
int aux=0;
int enter=1;
for (int i = 0; i < te.length; i++) {
aux+=AnchoContenido(te[i], tempo.getFont());
if(aux>=AREAVISIBLE.getWidth()){enter++;aux=AnchoContenido(te[i], tempo.getFont());}
if(te[i].indexOf(".__._..__:.__..-_...-__.")>=0){enter+=te[i].split(".__._..__:.__..-_...-__.").length;aux=0;}
}
//this result supposed to be the pointy
System.out.println((enter*tempo.getFontMetrics(tempo.getFont()).getHeight()));
pointy=(enter*tempo.getFontMetrics(tempo.getFont()).getHeight());
pointx=(pointx<tempo.getCaret().getMagicCaretPosition().x)?tempo.getCaret().getMagicCaretPosition().x+50:tempo.getCaret().getMagicCaretPosition().x-50;
ColocarPuntoVista(pointx,pointy);
}
}
});
}
public int AnchoContenido(String texto, Font formato){
return new JLabel().getFontMetrics(formato).stringWidth(((texto.equals("")?" ":texto)));
}
this is my old code:
if(OBJETO instanceof JTextComponent){
JTextComponent objetotexto=(JTextComponent)OBJETO;
objetotexto.addCaretListener(new CaretListener() {
int pointx=0,pointy=0;
@Override
public void caretUpdate(CaretEvent e) {
JTextComponent tempo=((JTextComponent)e.getSource());
if(tempo.getCaret().getMagicCaretPosition()!=null){
pointx=(pointx<tempo.getCaret().getMagicCaretPosition().x)?tempo.getCaret().getMagicCaretPosition().x+50:tempo.getCaret().getMagicCaretPosition().x-50;
pointy=(pointy<tempo.getCaret().getMagicCaretPosition().y)?tempo.getCaret().getMagicCaretPosition().y:tempo.getCaret().getMagicCaretPosition().y;
ColocarPuntoVista(pointx,pointy);
}
}
});
}
this is a perspective of I want
I need the exact position of the carect
Thanks for your advices and answers, i'm not very well with english sorry for my way to write