2021-09-22 GUI(鼠标事件)
2021-10-22 本文已影响0人
Denholm
import java.awt.*;
import java.awt.event.*;
public class MouseAndKeyEvent {
//定义该图形中所需的组件的引用
private Frame f;
private Button btn;
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");
f.add(btn);
myEvent();
f.setVisible(true);
}
private void myEvent() {
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
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();
}
}