2 yellowfarf yellowFARF 于 2015.07.27 18:37 提问

java监听器不起作用的问题 5C

package J_Fram;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;

public class KeyDemo{
JFrame f;
Container container;
JLabel jl;
JTextField ja;

public KeyDemo() {
    // TODO Auto-generated constructor stub
    f = new JFrame("键盘输入案例");
    f.setLayout(new FlowLayout());
    f.setBounds(400, 200, 300, 180);

    jl = new JLabel("只能输入数字");
    ja =new JTextField(10);
    f.add(jl);
    f.add(ja);


    ja.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
                char c;
                c = e.getKeyChar();

                if(!(c>='0' && c<='9'))
                {
                    System.out.println(c);
                    e.consume();
                }

        }

    });



    f.setVisible(true);
}




public static void main(String[] args) {
    // TODO Auto-generated method stub
    KeyDemo keyDemo = new KeyDemo();
}

}

3个回答

tongyi55555
tongyi55555   2015.07.27 18:44

只输入数字的条件是if ((c >= '0' && c <= '9')),去掉里面的感叹号。

sina_2831808769
sina_2831808769   Rxr 2015.07.27 20:56

键盘输入打印出来一下看看是不是ascii值

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.07.27 21:35

如果是0-9,则输出,感叹号的问题

Csdn user default icon
上传中...
上传图片
插入图片