/*
在窗口的TextField区域中,要求输入的只能是数字。当我写完代码测试时,发现不管是输入数字还是字母
程序都会提示 .....是非法的。然后就对照老毕的代码找我自己代码的错误,怎么看都没问题。就复制了老师的代码运行一遍,
还是一样的问题!!!纠结了一下午,终于发现是按的键有问题。if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)) 此处代码判断的
是键盘的上面一排的数字键,将小键盘的数字也给排除了!!!。因为每个键都对应一个不同code,键盘上面的数字键和小键盘的也不同。
*/
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");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf = new TextField(20);
but = new Button("my button");
f.add(tf);
f.add(but);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
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添加一个键盘监听。
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());
}
});
/*
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("action ok");
}
});
*/
/*
but.addMouseListener(new MouseAdapter()
{
private int count = 1;
private int clickCount = 1;
public void mouseEntered(MouseEvent e)
{
System.out.println("鼠标进入到该组件"+count++);
}
public void mouseClicked(MouseEvent e)
{
if(e.getClickCount()==2)
System.out.println("双击动作"+clickCount++);
}
});
*/
}
public static void main(String[] args)
{
new MouseAndKeyEvent();
}
}
|