JTextArea 定位到指定行

Eclipse中的Ctrl+L快捷键可以弹出定位指定行对话框,基于JTextArea仿照了一个,运行效果如下:


JTextArea 定位到指定行

代码如下:

 

/**
	 * 弹出定位行对话框
	 */
	private void showLocationLineDialog(){
		
		//取得总行数
		int totalLineCount = jTextArea1.getLineCount();
		if(totalLineCount <= 1){
			return ;
		}
		String title = "跳转至行:(1..."+totalLineCount+")";
		String line = JOptionPane.showInputDialog(this,title);
		if(line==null||"".equals(line.trim())){
			return;
		}	
		try {
			int intLine = Integer.parseInt(line);
			if(intLine > totalLineCount){
				return;
			}
			//JTextArea起始行号是0,所以此处做减一处理
			int selectionStart = jTextArea1.getLineStartOffset(intLine-1);
			int selectionEnd = jTextArea1.getLineEndOffset(intLine-1);
			
			//如果是不是最后一行,selectionEnd做减一处理,是为了使光标与选中行在同一行
			if(intLine != totalLineCount){
				selectionEnd--;
			}
			jTextArea1.setSelectionStart(selectionStart);
			jTextArea1.setSelectionEnd(selectionEnd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 

 

http://huangqiqing123.iteye.com/blog/1673636

你可能感兴趣的:(JTextArea)