声明:该程序是从core java中copy过来的,用于个人学习。
测试鼠标的响应的事件
- import javax.swing.*;
- import java.util.*;
- import java.awt.geom.*;
- import java.awt.event.*;
- import java.awt.*;
- public class MouseTest {
- public static void main(String[]args){
- MouseFrame frame=new MouseFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.show();
- }
- }
- class MouseFrame extends JFrame{
- public MouseFrame(){
- setTitle("MouseTest--phenix");
- setSize(this.DEFAULT_WIDTH,this.DEFAULT_HEIGHT);
- MousePanel panel=new MousePanel();
- Container contentPane=getContentPane();
- contentPane.add(panel);
- }
- public static final int DEFAULT_WIDTH=300;
- public static final int DEFAULT_HEIGHT=300;
- }
- class MousePanel extends JPanel{
- private static final int SIDELENGTH=20;
- private ArrayList squares;
- private Rectangle2D current;
- public MousePanel(){
- squares =new ArrayList();
- current=null;
- addMouseListener(new MouseHandler());
- addMouseMotionListener(new MouseMotionHandler());
- }
- public Rectangle2D find(Point2D p){
- for(int i=0;i<squares.size();i++){
- Rectangle2D r=(Rectangle2D)squares.get(i);
- if(r.contains(p))return r;
- }
- return null;
- }
- //添加一个矩形
- public void add(Point2D p){
- double x=p.getX();
- double y=p.getY();
- current=new Rectangle2D.Double(x-SIDELENGTH/2,y-SIDELENGTH/2,SIDELENGTH,SIDELENGTH);
- squares.add(current);
- repaint();
- }
- //移除矩形
- public void remove(Rectangle2D p){
- if(p==null)return;
- if(p==current)current=null;
- squares.remove(p);
- repaint();
- }
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- Graphics2D g2=(Graphics2D)g;
- for(int i=0;i<squares.size();i++){
- g2.draw((Rectangle2D)squares.get(i));
- }
- }
- private class MouseHandler extends MouseAdapter{
- public void mousePressed(MouseEvent event){
- current=find(event.getPoint());
- if(current==null){
- add(event.getPoint());
- }
- }
- public void mouseClicked(MouseEvent event){
- current=find(event.getPoint());
- if(current!=null&&event.getClickCount()>=2){
- remove(current);
- }
- }
- }
- private class MouseMotionHandler implements MouseMotionListener{
- public void mouseMoved(MouseEvent event){
- if(find(event.getPoint())==null){
- setCursor(Cursor.getDefaultCursor());
- }
- else
- {
- setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
- }
- }
- public void mouseDragged(MouseEvent event){
- if(current!=null){
- int x=event.getX();
- int y=event.getY();
- current.setFrame(x-SIDELENGTH/2,y-SIDELENGTH/2,SIDELENGTH,SIDELENGTH);
- repaint();
- }
- }
- }
- }