JTextArea中光标的操作

来源:互联网 发布:阿里云域名认证失败 编辑:程序博客网 时间:2024/05/16 11:32

获取光标所在行数,列数:

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);    }}

这里写图片描述

0 0