单击后保持mousePressed处于活动状态

时间:2015-11-05 22:04:33

标签: java mouse

所以我想要做的是在一次点击之后保持mousePressed方法' on'即使我不是自己压低它。然后在另一次点击后,它将关闭'关闭

addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            // save coord x,y when mouse is pressed
            oldX = e.getX();
            oldY = e.getY();
        }
    });

    addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {

            // coord x,y when drag mouse
            currentX = e.getX();
            currentY = e.getY();

            if (g2 != null) {
                // draw oval if g2 context not null
                g2.drawOval(oldX, oldY, width, height);
                g2.fillOval(oldX, oldY, width, height);

                // refresh draw area to repaint
                repaint();

                // store current coords x,y as olds x,y
                oldX = currentX;
                oldY = currentY;
            }
        }
    });

1 个答案:

答案 0 :(得分:1)

  1. 处理mousePressed()事件。然后在你的班级中保留一个变量(比方说" clickCounter"),每次生成事件时你都会增加。

  2. 然后您需要处理mouseMoved()事件以了解鼠标何时移动。

  3. 所以现在你在mouseMoved()事件中的逻辑可以检查变量是否为奇数,这表示刚刚点击了鼠标:

    if (clickCounter % 2 == 1)
    {
        add your logic here
    }
    

    或者你可以保留一个布尔变量,你可以在每次点击鼠标时关闭/打开它。