import java.awt.*;
import java.awt.event.*;
class MouseAndKeyEvent
{
private Frame f;
private Button but;
private TextField tf;
MouseAndKeyEvent()
{
ini();
}
public void ini()
{
f = new Frame("我的窗口");
f.setBounds(300,200,500,400);
f.setLayout(new FlowLayout());
tf =new TextField(10);
but = new Button("转到");
f.add(tf);
f.add(but);
myEvent();
f.setVisible(true);
}
public void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
/*
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent 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 ))
{
e.consume();//我已经用了consume方法了为什么,非数字字符还是进来了呢
final Dialog dia = new Dialog(f,"提示信息",true);
dia.setBounds(300,200,200,100);
dia.setLayout(new FlowLayout());
Label lab = new Label("错误字符",Label.CENTER);
Button b =new Button("确定");
dia.add(lab);
dia.add(b);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dia.setVisible(false);
}
});
dia.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dia.setVisible(false);
}
});
dia.setVisible(true);
}
}
});
}
public static void main(String[] args)
{
new MouseAndKeyEvent();
}
}
问题写在上面,大家可以运行一下,出来的文本框本来是可以输入0—9之外的字符的,加了consume方法之后应该不可以呀??
为什么在弹出对话框的时候,这些字符又进入文本框里呢???
还有就是怎么实现可以在文本框中实现退格键,并且不弹出对话框??
求指教????
|