JTextArea的多行整体左缩进与右缩进

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

public class Indentation extends JFrame implements KeyListener{
	public static final int WIDTH = 1000;
	public static final int HEIGHT = 700;
	JTextArea ta;
	
	public Indentation() {
		initialize();
	}
	
	public void initialize() {
		ta = new JTextArea();
		ta.addKeyListener(this);
		Container c = this.getContentPane();
		c.setLayout(new BorderLayout());
		c.add(ta, BorderLayout.CENTER);
		setBounds(100, 100, WIDTH, HEIGHT);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}
	
	public static void main(String args[]) {
		new Indentation();
	}

	public void keyPressed(KeyEvent e) {
		//在Eclipse中是通过Tab来实现的,但在JTextArea控件中按Tab键的时候是当作输入'\t'字符来处理的,所以换成Ctrl+Q快捷键来实现
		if(e.isControlDown() && KeyEvent.VK_Q == e.getKeyCode()) {
			//多行右整体缩进
			String text = ta.getText();
			int start = ta.getSelectionStart();
			int end = ta.getSelectionEnd();
			int startRow = 0;
			int endRow = 0;
			int n = 0; 
			try {
				startRow = ta.getLineOfOffset(start);
				endRow = ta.getLineOfOffset(end);
				//n = endRow - startRow;
				while(endRow >= startRow) {
					end = text.substring(0, end).lastIndexOf(10);
					ta.insert("\t",end+1);
					//ta.replaceRange("\t", end, end+1);
					endRow --;
				}
			} catch (BadLocationException e1) {
				e1.printStackTrace();
			}
		}else if(e.isShiftDown() && KeyEvent.VK_TAB == e.getKeyCode()) {
			//多行左整体取消缩进
			int start = ta.getSelectionStart();
			int end = ta.getSelectionEnd();
			int startRow = 0;
			int endRow = 0;
			int n = 0; 
			try {
				startRow = ta.getLineOfOffset(start);
				endRow = ta.getLineOfOffset(end);
				//n = endRow - startRow;
				while(endRow >= startRow) {
					end = ta.getText().substring(0, end).lastIndexOf(10);
					if(ta.getText().charAt(end+1) == '\t') {
						ta.replaceRange("", end+1, end+2);
					}
					endRow --;
				}
			} catch (BadLocationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
		}
	}

	public void keyReleased(KeyEvent arg0) {		
	}

	public void keyTyped(KeyEvent arg0) {		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值