• java事件处理3


    鼠标拖动事件

    接口MouseMotionListener

    两个方法

    mouseDragged(MouseEvent)//拖动鼠标
    mouseMoved(MouseEvent)//移动鼠标

    一个拖动按钮的例子

    public class test{
    
        public static void main(String args[]){
            MyWin window1=new MyWin();
            window1.setBounds(12,12,300,300);
        }
    }
    
    class MyWin extends JFrame{
        MousePolice mouseListener1;
        MyWin(){
            init();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        void init(){
            mouseListener1=new MousePolice();
            add(mouseListener1,BorderLayout.CENTER);
        }
    }
    
    class MousePolice extends JLayeredPane implements MouseListener,MouseMotionListener{
        JButton button1;
        int x,y,a,b,x0,y0;
        MousePolice(){
            button1=new JButton("move me");
            button1.addMouseListener(this);
            button1.addMouseMotionListener(this);
            setLayout(new FlowLayout());
            add(button1,JLayeredPane.DEFAULT_LAYER);
        }
        public void mousePressed(MouseEvent e){
    //        JComponent e1=(JComponent)e.getSource();
    //        setLayer(e1,JLayeredPane.DRAG_LAYER);//不明白书上有何用意
    //        a=e1.getBounds().x;
    //        b=e1.getBounds().y;
            x0=e.getX();
            y0=e.getY();
            System.out.println("11");
        }
        public void mouseReleased(MouseEvent e){
    //        JComponent e1=(JComponent)e.getSource();
    //        setLayer(e1,JLayeredPane.DEFAULT_LAYER);
    //        System.out.println("22");
        }
        public void mouseEntered(MouseEvent e){}
        public void mouseExited(MouseEvent e){}
        public void mouseClicked(MouseEvent e){}
        public void mouseMoved(MouseEvent e){}
        public void mouseDragged(MouseEvent e){
            Component com=null;
            if(e.getSource() instanceof JButton){
                com=(Component)e.getSource();
                a=com.getBounds().x;
                b=com.getBounds().y;
                x=e.getX();
                y=e.getY();
                com.setLocation(a+x-x0,b+y-y0);//公式:组件地址+现在鼠标地址-之前鼠标地址
                System.out.println("33");
            }
        }
    }
  • 相关阅读:
    hdoj 4251 The Famous ICPC Team Again
    hdoj 1879 最小生成树之继续畅通工程
    并查集之Dragon Balls
    并查集之 Is It A Tree?
    hdoj 1874最短路之畅通工程续
    1040: Count
    hdoj 1874最短路之最短路径问题
    并查集之小希的迷宫
    并查集之食物链
    Ordered Fractions
  • 原文地址:https://www.cnblogs.com/vhyc/p/5991787.html
Copyright © 2020-2023  润新知