如下练习:




java 按下鼠标左键 java移动鼠标光标_sed


主要利用鼠标移动事件和(按下、释放、单击、进入或离开)鼠标事件,当鼠标点击时,发生mousePressed事件,判断鼠标点击的坐标是否在圆内,在移动鼠标,发生mouseDragged事件,

如果鼠标刚开始按下时在圆内,按下移动鼠标时,更新圆的坐标,当释放鼠标时,移动圆结束。

鼠标移动事件需要实现下面两个方法:

public void mouseDragged(MouseEvent e)鼠标按键在组件上按下并拖动时调用。在释放鼠标按键前,MOUSE_DRAGGED 事件被连续地传递到发起该拖动的组件(而不管鼠标位置是否处于该组件的边界内)。 
public void mouseMoved(MouseEvent e)鼠标光标移动到组件上但无按键按下时调用。

面板代码如下:

class OvalMove extends JPanel implements MouseMotionListener,MouseListener
{
    int x,y;
    boolean flag = false;
    boolean isClickinCircle = false;
    int radius = 20;
    int dx,dy;
    public OvalMove()
    {
        dx = 0;
        dy = 0;
        x = 146;
        y = 120;
        addMouseMotionListener(this);
        addMouseListener(this);
        
    }
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillOval(x, y, radius, radius);
    }
    public Dimension getPreferredSize()
    {
        return new Dimension(500,300);
    }
    
    public void mouseClicked(MouseEvent e) {}
    @Override
    public void mousePressed(MouseEvent e)
    {
        int x1 = e.getX();
        int y1 = e.getY();
        int dist = (x1-x-radius/2)*(x1-x-radius/2) + (y1-y-radius/2)*(y1-y-radius/2);
        if(dist<=radius*radius/4) 
        {
            dx = x1-x;
            dy = y1-y;
            isClickinCircle = true;
        }
        else
            
            isClickinCircle = false;
        System.out.println(e.getX()+":"+e.getY());
    }
    public void mouseReleased(MouseEvent e)
    {
        isClickinCircle = false;
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseDragged(MouseEvent e)
    {
        if(isClickinCircle)
        {
            x = e.getX()-dx;
            y = e.getY()-dy;
            repaint(); 
        }
            System.out.println(":"+e.getX()+":"+e.getY());  
    }
  
    public void mouseMoved(MouseEvent e) {} 
}

圆的坐标初始值是具体值,设置了圆的填充色。效果如下:


java 按下鼠标左键 java移动鼠标光标_开发语言_02


这里主要是解决问题的思路,供大家参考。

由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。