java的鼠標移動事件
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);
}
}
}
java的鼠標移動事件相關文章:
2.如何設置鼠標事件
4.鼠標事件屬性詳解