import java.awt.*;
import java.awt.event.*;
class MouseAndKeyEvent
{
private Frame f;
private Button but;
private TextField tf1;
private TextField tf2;
MouseAndKeyEvent()
{
init();
}
public void init()
{
f = new Frame("my frame");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf1 = new TextField(20);
tf2 = new TextField(20);
but = new Button("my button");
f.add(tf1);
f.add(tf2);
f.add(but);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf1.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();
}
}
});
tf2.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添加一个键盘监听。
but.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)
//System.exit(0);
System.out.println("ctrl+enter is run");
//System.out.println(KeyEvent.getKeyText(e.getKeyCode())+"...."+e.getKeyCode());
}
});
}
public static void main(String[] args)
{
new MouseAndKeyEvent();
}
}
//问题是,如果我有很多个文本框都要添加同一个事件,目前只会tf1. tf2. 怎么能简化下代码?