日期:2014-05-20  浏览次数:20819 次

JTextField屏蔽数字时consumer()无效而TextField有效
本帖最后由 wu862431048 于 2013-06-16 22:00:35 编辑
代码如下,用swing仍然可以输入字符
public class test5 extends JFrame {

public test5() {
JTextField field = new JTextField(10);
field.addKeyListener(new KeyAdapter() {
//添加事件监听
public void keyPressed(KeyEvent e)
{
System.out.println(e.getKeyCode());
if(!(e.getKeyCode()>=KeyEvent.VK_0 && e.getKeyCode()<=KeyEvent.VK_9))
{
e.consume();//?????怎么没用效啊
}
}
});


this.add(field);
this.setLayout(new FlowLayout());
this.setBounds(100, 200, 300, 100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new test5();
}

}




用AWT写,如下,非数字无法输入
public class test7 extends Frame {
public test7() {
TextField field = new TextField(10);
field.addKeyListener(new KeyAdapter() {
//添加事件监听
public void keyPressed(KeyEvent e)
{
System.out.println(e.getKeyCode());
if(!(e.getKeyCode()>=KeyEvent.VK_0 && e.getKeyCode()<=KeyEvent.VK_9))
{
e.consume();
}
}
});
this.add(field);
this.setLayout(new FlowLayout());
this.setBounds(100, 200, 300, 100);
this.add(new Label("AWT 不能输入字符"));
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

public static void main(String[] args)
{
new test7();
}

}

Java consume() swing和awt JTextField和TextField

------解决方案--------------------
使用 keyTyped 方法。
------解决方案--------------------
#3说的对。
public class test5 extends JFrame {

public test5() {
JTextField field = new JTextField(10);
field.addKeyListener(new KeyAdapter() {
//添加事件监听
public void keyTyped(KeyEvent e)
{
// System.out.println(e.getKeyCode());
if(!(e.getKeyChar()>=KeyEvent.VK_0 && e.getKeyChar()<=KeyEvent.VK_9))
{

e.consume();//?????怎么没用效啊
}
}
});
this.add(field);
this.setLayout(new FlowLayout());
this.setBounds(100, 200, 300, 100);
this.setVisible(true);