鼠标拖动事件
接口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");
}
}
}