Java中的鼠標和鍵盤事件
鼠標事件有
鼠標事件類型是MouseEvent
getX()
getModifiers() 獲取鼠標左鍵或者右鍵
getClickCount() 獲取鼠標被點擊的次數
getSource() 獲取鼠標發生的事件源
事件源獲得監視器的方法是addMouseListener()
處理事件源發生的時間的事件的接口是MouseListener 接口中有如下的方法
mousePressed(MouseEvent) 負責處理鼠標按下事件
mouseReleased(MouseEvent) 負責處理鼠標釋放事件
mouseEntered(MouseEvent) 負責處理鼠標進入容器事件
mouseExited(MouseEvent) 負責處理鼠標離開事件
mouseClicked(MouseEvent) 負責處理點擊事件
事件源發生的鼠標事件有
鼠標事件的類型是MouseEvent
事件源獲得監視器的方法是addMouseMotionListener()
處理事件源發生的事件的接口是MouseMotionListener 接口中有如下的方法
mouseDragged() 負責處理鼠標拖動事件
mouseMoved() 負責處理鼠標移動事件
setCursor(Cursor
鍵盤事件源使用addKeyListener 方法獲得監視器
鍵盤事件的接口是KeyListener 接口中有
public void keyPressed(KeyEvent e) 按下鍵盤按鍵
public void keyReleased(KeyEvent e) 釋放鍵盤按鍵
public void keyTypde(KeyEvent e) 按下又釋放鍵盤按鍵
package mouseenvent;
import java
import javax
import java
public class Mouse extends JFrame implements MouseListener{
JPanel jp = new JPanel();
JLabel statusbar = new JLabel();
static final long serialVersionUID=
public Mouse(){
setTitle(
getContentPane()
getContentPane()
jp
}
public static void main(String[] args){
Mouse frame = new Mouse();
frame
frame
frame
}
public void mousePressed(MouseEvent e){
int x = e
int y = e
String s =
statusbar
}
public void mouseReleased(MouseEvent e){
int x = e
int y = e
String s =
statusbar
}
public void mouseClicked(MouseEvent e){
int x = e
int y = e
String s =
statusbar
}
public void mouseEntered(MouseEvent e){
int x = e
int y = e
String s =
statusbar
}
public void mouseExited(MouseEvent e){
int x = e
int y = e
String s =
statusbar
}
}
package mouseenvent;
import java
import javax
import java
public class MouseMotion extends JFrame implements MouseMotionListener{
static final long serialVersionUID=
JLabel bar = new JLabel();
JTextField text = new JTextField();
public MouseMotion(){
setTitle(
getContentPane()
getContentPane()
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e){
int x = e
int y = e
String s =
bar
text
}
public void mouseDragged(MouseEvent e){
int x = e
int y = e
String s =
bar
text
}
public void mouseMoved(MouseEvent e){
int x = e
int y = e
String s =
bar
text
}
public static void main(String args[])throws Exception{
MouseMotion mouse = new MouseMotion();
mouse
mouse
mouse
}
}
package mouseenvent;
import java
import javax
import java
public class Key extends JFrame implements KeyListener{
JLabel bar ;
public Key(){
bar = new JLabel();
getContentPane()
addKeyListener(this);
}
public void keyPressed(KeyEvent e){
char c = e
String s = c+
bar
}
public void keyReleased(KeyEvent e){
char c = e
}
public void keyTyped(KeyEvent e){
char c = e
}
public static void main(String args[])throws Exception{
Key key = new Key();
key
key
key
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25830.html