您的位置:首页 > 其它

JTextArea中光标的操作

2016-03-15 13:15 337 查看
获取光标所在行数,列数:

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import java.awt.*;

public class Test extends JFrame {

public static void main(String[]args){
new Test().launch();
}

public void launch(){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}   catch(Exception e){
e.printStackTrace();
}
Box content = Box.createVerticalBox();
final JTextArea textArea = new JTextArea();
final JTextField info = new JTextField();
info.setMinimumSize(new Dimension(300,50));
info.setMaximumSize(new Dimension(300,50));
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
try{
//获取光标位置,距离起始位置的偏移量
int posi = textArea.getCaretPosition();
//计算行数,比较奇芭,能用,有待搞懂
Rectangle rec = textArea.modelToView(posi);
int rows = rec.y / rec.height + 1;
//计算列数用上面的方法就不行了,先获取所在行r,但是如果设置了自动换行的话,这个r目测不好用,
int r = textArea.getLineOfOffset(posi);
//用光标偏移量减去行首偏移量就是列数了,
int columns = posi - textArea.getLineStartOffset(r) + 1;
info.setText("行数:" + rows + "    列数:" + columns);
}   catch(BadLocationException badlocation){
System.out.println("bad location");
}
}
});
content.add(info);
content.add(textArea);
this.add(content);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(300,200);
setSize(300,200);
setVisible(true);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: