现在的位置: 首页 > 综合 > 正文

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

2012年02月24日 ⁄ 综合 ⁄ 共 1810字 ⁄ 字号 评论关闭
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) {		
	}
}

抱歉!评论已关闭.