鼠标事件代码示例: import java.awt.*; import java.awt.event.*; class MouseAndKeyEvent { private Frame f; private Button but; private TextField tf;
MouseAndKeyEvent() { init(); }
public void init() {
f=new Frame("my frame"); //对frame进行基本设置 f.setBounds(400,200,500,300); f.setLayout(new FlowLayout());
tf=new TextField(20);
but=new Button("my but"); //讲组件添加到frame中
f.add(tf); f.add(but); //加载一下窗体上的事件 myEvent(); //显示窗体 f.setVisible(true); }
private void myEvent() {
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.out.println("我被关闭了 "); System.exit(0); }
});
tf.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int code=e.getKeyCode(); if(!(code>=KeyEvent.VK_0&&code<=KeyEvent.VK_9)) { System.out.println(code+"...是非法的"); e.consume(); } }
}); but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("action ok"); } }); but.addMouseListener(new MouseAdapter() { private int a=1; public void mouseEntered(MouseEvent e) { System.out.println("鼠标进入到该组件"+a+++"次");
} public void mouseClicked(MouseEvent e) { if(e.getClickCount()==2) System.out.println("双击动作"); } });
but.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_ENTER&&e.isControlDown()) System.out.println("ctrl and enter run"); //System.exit(0); //System.out.println(KeyEvent.getKeyText(e.getKeyCode())+"..."+e.getKeyCode()); } });
}
public static void main(String[] args) {
new MouseAndKeyEvent(); } } |