本帖最后由 工善器 于 2013-10-20 21:01 编辑
/*
鼠标和键盘事件的例子
*/
package en.itcast.java.tools;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MouseAndKeyEvent {
private Button b;
private Frame f;
private TextField t;
MouseAndKeyEvent()
{
init();
}//这是抽象方法么,构造方法
public void init()
{
//先设置好快框架
f=new Frame();
f.setBounds(400,300,200,300);
f.setLayout(new FlowLayout());
f.setVisible(true);
t=new TextField();
b=new Button("按钮");
f.add(t);
f.add(b);
myEvent();
}//方法的重写?
private void myEvent()
{
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
t.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();
}
}
});
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
{
System.out.println("ctrl enter is run!");
}
}
});
}
public static void main(String[] args) {
new MouseAndKeyEvent();
}
}
|
|