IN JAVA swing文本框只接受数值和一次(+, - ,.)

时间:2015-01-07 16:15:24

标签: java swing textbox keypress keyevent

/ * 我正在尝试使用Java / eclipse创建一个TEXTBOX。     文本框仅通过键盘接受数值     并且那已经使用了swing     +唱"单次"在"第一个位置"      - 唱"单次"在"第一个位置"     。期间"单次" at"任何位置"     完美地删除和退格工作 * /

import javax.swing.*;  
import java.awt.event.KeyEvent;  
import java.awt.event.KeyListener;  

public class NumericBox extends JApplet{ 
    //making textfield
    static JTextField tf = new JTextField();  
    //main start
    public static void main(String arh[]){  

        NumericBox g = new NumericBox();  
        Handle h = g.new Handle();  
        JFrame f = new JFrame();  //frame
        JPanel p = new JPanel();  //pannel

        tf.setColumns(5);  
        tf.addKeyListener(h);  

        p.add(tf);    
        f.add(p);  
        f.setSize(200,100);  
        f.setVisible(true);  

    }//end of main method  
   // to use only numaric key implementation

    private class Handle implements KeyListener{  

        public void keyTyped(KeyEvent e) {
            char vChar = e.getKeyChar();
            if (!(Character.isDigit(vChar)
                  || (vChar == KeyEvent.VK_BACK_SPACE)
                  || (vChar == KeyEvent.VK_CLEAR)
                  || (vChar == KeyEvent.VK_PERIOD)
                  || (vChar == KeyEvent.VK_PLUS)
                  || (vChar == KeyEvent.VK_MINUS))) {
                getToolkit().beep();
                e.consume();
            }

       /*    if(vChar == KeyEvent.VK_PERIOD){
                            if(i==1)
                                e.consume();
                            else
                                i=1;
                        }
         */ 
        }

        public void keyPressed(KeyEvent e) {}  //keyPressed  events
        public void keyReleased(KeyEvent e) {}  //keyReleased events

    }//end of inner class  

}//end of outer class  

2 个答案:

答案 0 :(得分:0)

验证文本将通过正则表达式得到最佳处理。至于捕获值更改,请按照此处的示例查找Swing提供的基础文档:https://stackoverflow.com/a/3953219/1843508

答案 1 :(得分:0)

你可以使用JFormattedTextField或@Ofer Lando说,使用regex(正则表达式)

实施例,

private boolean containsNumber(String sentence)
{
    Pattern patt = Pattern.compile(".*?[0-9].*");
    Matcher m = patt.matcher(sentence);
    return m.matches();
}