java的鼠标移动事件
相关话题
爱学习的小伙伴们,可能都可能都学过Java,但是你知道java的鼠标移动事件是什么吗?不知道的话跟着小编一起来学习了解java的鼠标移动事件。
java的鼠标移动事件代码介绍
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class mymouse {
static JFrame frm;
static JTextField tf;
static JButton btn;
static int x, y,px, py,bx,by,offx,offy; //
public static void main(String[] args) {
frm = new JFrame("dialog");
frm.setBounds(400, 100, 500, 400);
frm.setLayout(null);
tf = new JTextField();
tf.setBounds(60,200,200,20);
btn = new JButton("move me");
btn.setBounds(60,40,100,50);
frm.add(tf);
frm.add(btn);
btn.addMouseMotionListener(new mymousemotion());
btn.addMouseListener(new mymouselistener());
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static class mymousemotion implements MouseMotionListener{
public void mouseDragged(MouseEvent e) {
//
x=e.getX()-px+bx;
y=e.getY()-py+by;
btn.setLocation(x, y);
tf.setText("button location :"+x+","+y);
bx=x;
by=y;
}
public void mouseMoved(MouseEvent e) {
}
}
static class mymouselistener extends MouseAdapter{
public void mousePressed(MouseEvent e){
//鼠标点击位置相对 btn 的坐标.
px=e.getX();
py=e.getY();
//获取 btn 相对 frm 的坐标
bx=btn.getLocation().x;
by=btn.getLocation().y;
String str=px+","+py+" . "+bx+","+by;
tf.setText(str);