import java.awt.*;
import java.awt.event.*;
public class MouseAndKeyEvent {
// 定义该图形中所需的组件的引用
private Frame f;
private Button btn;
private TextField textField;// 文本框
public MouseAndKeyEvent() {
init();
}
private void init() {
f = new Frame("my frame");
f.setBounds(300, 100, 500, 400);
f.setLayout(new FlowLayout());
btn = new Button("my Button");
textField = new TextField(20);
f.add(textField);
f.add(btn);
myEvent();
f.setVisible(true);
}
private void myEvent() {
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 文本框监听
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (!(code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9)) {
// System.out.println(code + "是非法的");
e.consume();
}
}
});
// 给btn添加一个键盘监听
btn.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// System.exit(0);
// }
// 组合键ctrl+Enter
if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) {
// System.exit(0);
System.out.println("ctrl + enter is run");
}
// System.out.println(e.getKeyChar() + "..." + e.getKeyCode());
// System.out.println(KeyEvent.getKeyText(e.getKeyCode()) +
// "..." + e.getKeyCode());
}
});
btn.addActionListener(e -> System.out.println("action ok"));
btn.addMouseListener(new MouseAdapter() {
private int count = 0;
private int clickCount = 0;
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("鼠标进入到该组件:" + count++);
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2)
System.out.println("双击动作:" + clickCount++);
}
});
}
public static void main(String[] args) {
new MouseAndKeyEvent();
}
}
网友评论