import java.awt.*;
import java.awt.event.*;import javax.swing.SwingUtilities;
class WinB extends Frame implements MouseListener,MouseMotionListener
{ Button button;
  TextField text;
  int x, y;
  boolean move=false;
  WinB()
   { button=new Button("用鼠标拖动我");
 text=new TextField("用鼠标拖动我",8);
 button.addMouseListener(this);
 button.addMouseMotionListener(this);
 text.addMouseListener(this);
 text.addMouseMotionListener(this);
 addMouseMotionListener(this);
 setLayout(new FlowLayout());
 add(button);
 add(text);
 addWindowListener(new WindowAdapter(){
         public void windowClosing(WindowEvent e){
             System.exit(0);
         }
     });
 setBounds(10,10,350,300);
 setVisible(true);
 validate();  
   }
  public void mousePressed(MouseEvent e){}
  public void mouseReleased(MouseEvent e)
  { move=false;
  
  }
  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 Component) 
{  com=(Component)e.getSource(); 
if(com!=this)
move=true;
      e=SwingUtilities.convertMouseEvent(com, e, this);
  
   if(move)
   { x=e.getX();
     y=e.getY();
 int w=com.getWidth();
 int h=com.getHeight();
 com.setLocation(x-w/2, y-h/2);
   }   
}
  }
}     
public class MouseMotionExa { /**
 * @param args
 */
public static void main(String[] args) {
new WinB();
// TODO Auto-generated method stub }}
这个程序是是实现通过鼠标来拖动组件,
if(e.getSource() instanceof Component)这条语句主要是控制什么情况,事件源对象
一定是组件类的对象,没有必要啊?x = e.getX();
  y = e.getY();
  int w = com.getSize().width;
  int h = com.getSize().height;
  com.setLocation(x - w / 2, y - h / 2);
  }当我的鼠标指针并不指向组件的中心时,促发拖动鼠标事件,鼠标指针自动跳到组件的中心,这是怎么实现的???就我看上面的几句,只有鼠标指针在组件的中心时,鼠标指针移动时才会在中心啊?

解决方案 »

  1.   

    http://zhidao.baidu.com/question/50570754.html[code=java]public void mouseDragged(MouseEvent e) { Component com = null ; //窗口if (e.getSource() instanceof Component ) //判断鼠标的动作是不是窗口的对象。{ com=(Component)e.getSource(); //实例化这个动作if (com!=this) //假如不是在窗口中拖动鼠标 move = true ; e=SwingUtilities.convertMouseEvent(com,e,this); //转移鼠标事件到窗口 if (move) //如果不是在窗口中拖动鼠标 ,即鼠标出去了{ x = e.getX(); //获取鼠标在窗口中的位置坐标 y = e.getY(); int w = com.getSize().width, h = com.getSize().height; com.setLocation(x-w/2,y-h/2); //把窗口的位置重置到鼠标处} }