Using an if statement to test if JTextField is an integer

后端 未结 3 1655
栀梦
栀梦 2021-01-28 02:07

I want my program to be able to tell if what is inside my two JTextFields is an integer or a String.

CODE

          public void actionP         


        
3条回答
  •  清酒与你
    2021-01-28 02:33

    You can process the key event in the action method also. Try this

    First make a JTextField

    JTextField j=new JTextField();
    

    Then add KeyListner to this JTextField as

        j.addKeyListener(new KeyListener() {
    
            @Override
            public void keyTyped(KeyEvent arg0) {
                // TODO Auto-generated method stub
    
            }
    
            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub
                if(arg0.getKeyCode()>57 || arg0.getKeyCode()<48) {
                        //your error message and other handling code here
                    JOptionPane.showMessageDialog(PatentFrame, "Only integer allowed", "Message title",JOptionPane.ERROR_MESSAGE);
                }
    
            }
    
            @Override
            public void keyPressed(KeyEvent arg0) {
                // TODO Auto-generated method stub
    
            }
        });
    

    48 is ASCII code for 0 and 57 is ASCII code for 9. You can also ignore virtual keys like shift. See ASCII chart

提交回复
热议问题