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); } }
相关文章推荐
- hdu-1754 I Hate It(线段树求区间最大值)
- android 采用windowmanager屏蔽HOME键
- html 写的一个登录界面
- 标准同步时钟解决方案
- “神秘”的加密指纹
- Android <shape>定义图形
- 已有数据库(单机)部署Database Vault
- 判断鼠标滚动方向 - 很好的思路
- classes could not be found: - android.support.v7.i
- C语言函数sscanf()的用法
- spring IOC的好处与坏处
- 【CSS疑难杂症】z-index 层级树
- HTML5——section,article,aside
- 位运算: 如何判断一个数是否是2的n次方
- 四种类型转换符
- Android自定义控件
- 矩阵分解——三角分解(二)
- SQL Server 2012 自动增长列,值跳跃问题
- Visual Studio调试小技巧
- python pip 安装包时出错