日期:2014-05-20 浏览次数:20886 次
import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; public class AA extends JFrame{ public static void main(String[] args) { new AA(); } public AA(){ setResizable(false); setSize(new Dimension(500,400)); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); initData(); } private void initData(){ this.add(new MyTextArea()); } /** * 自定义JTextArea * @author Administrator * */ private class MyTextArea extends JTextArea implements MouseMotionListener,MouseListener{ private Point pressPoint; //按下时坐标位置 private Point currenPoint; //当前鼠标拖动时的位置 public MyTextArea(){ setPreferredSize(new Dimension(500,400)); setLineWrap(true); this.addMouseListener(this); this.addMouseMotionListener(this); setSelectionColor(Color.white); } public void paint(Graphics g){ super.paint(g); if(pressPoint != null && currenPoint != null){ g.setColor(Color.BLACK); int drawRectPara[] = new int[4]; //画矩形的4个参数 if(pressPoint.x < currenPoint.x){ drawRectPara[0] = pressPoint.x; drawRectPara[2] = currenPoint.x - pressPoint.x; }else{ drawRectPara[0] = currenPoint.x; drawRectPara[2] = pressPoint.x - currenPoint.x; } if(pressPoint.y < currenPoint.y){ drawRectPara[1] = pressPoint.y; drawRectPara[3] = currenPoint.y - pressPoint.y; }else{ drawRectPara[1] = currenPoint.y; drawRectPara[3] = pressPoint.y - currenPoint.y; } g.drawRect(drawRectPara[0],drawRectPara[1],drawRectPara[2],drawRectPara[3]); } } @Override public void mouseDragged(MouseEvent arg0) { // TODO Auto-generated method stub currenPoint = arg0.getPoint(); repaint(); } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub pressPoint = arg0.getPoint(); this.setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub pressPoint = null; this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } } }