Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: need help with consuming key events.

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default need help with consuming key events.

    I am trying to create an event handler for two JTextFields to only allow numerical input. It consumes all letter but for some reason the "n" key still gets through. I have the spaghetti code below. Can anyone tell me what i'm not getting?

    public void keyTyped(KeyEvent in) {
    		char input = in.getKeyChar();
    		if (in.getSource() == scaleField){
    			if (!(Character.isDigit(input) ||
    					(input==KeyEvent.VK_BACK_SPACE) ||
    					(input==KeyEvent.VK_DELETE) ||
    					(input==KeyEvent.VK_DECIMAL) ||
    					(input==KeyEvent.VK_PERIOD)) ||
    					(scaleField.getText().contains(".") &&
    					(input==KeyEvent.VK_DECIMAL ||
    					input==KeyEvent.VK_PERIOD))){
    				in.consume();
    			}
    		}else if (!(Character.isDigit(input) ||
    				(input==KeyEvent.VK_BACK_SPACE) ||
    				(input==KeyEvent.VK_DELETE))){
    			in.consume();
    		}
    	}


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    Can you make a small, complete program that compiles, executes and shows the problem?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need help with consuming key events.

    Thanks for the quick reply. Here it is:

    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
     
     
    public class Main extends JFrame implements KeyListener{
    	private static final long serialVersionUID = 1L;
    	JTextField inputField = new JTextField(20);
    	JPanel contentPane = new JPanel();
     
    	public Main(){
     
    		inputField.addKeyListener(this);
    		contentPane.add(inputField);
    		add(contentPane);
    		pack();
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		setVisible(true);
     
    	}
     
    	public static void main(String[] args) {
     
    		new Main();
     
    	}
     
    	@Override
    	public void keyPressed(KeyEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void keyReleased(KeyEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void keyTyped(KeyEvent k) {
    		char input = k.getKeyChar();
    		if (!(Character.isDigit(input) ||
    				(input==KeyEvent.VK_BACK_SPACE) ||
    				(input==KeyEvent.VK_DELETE) ||
    				(input==KeyEvent.VK_DECIMAL) ||
    				(input==KeyEvent.VK_PERIOD)) ||
    				(inputField.getText().contains(".") &&
    				(input==KeyEvent.VK_DECIMAL ||
    				input==KeyEvent.VK_PERIOD))){
    			k.consume();
    		}
     
    	}
     
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    The KeyEvent values are int, not char. Look at their values and see if (int)'n' is one of them.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jun 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need help with consuming key events.

    Hmmm. None are 'n'. All of the KeyEvents are actual integers. But it seems like somehow allowing decimals through is also allowing the "n" key through and even consuming the "n" key specifically before the main if statement doesn't catch it. Weird. Any recommendations?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    None are 'n'.
    No, there is one that has the value 'n'.
    Did you look at the values of the static KeyEvent variables that the code uses? Which one of them had the value: (int)'n'?
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    antihero.mc (June 27th, 2014)

  8. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: need help with consuming key events.

    I'm not sure you got Norm's point: The method getKeyChar() returns a char value, but the constants you're using for comparison are int values. The ASCII value of 'n' is 110 which, if you refer to this chart, you can see is the value for VK_DECIMAL.

    Think about that a while and see if you can come up with a solution.

    BTW - your runnable example is pretty good, but it's lacking in code to tell a person what's going on. I've improved it some so that you can see what's going on while the program is running. This is one of the techniques I recommend you use when debugging your code.
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
     
     
    public class TestClass extends JFrame implements KeyListener{
        private static final long serialVersionUID = 1L;
        JTextField inputField = new JTextField(20);
        JPanel contentPane = new JPanel();
     
        // GB: a variable in which to store accepted inputs
        StringBuilder inputString;
     
        public TestClass()
        {
            // GB: initialize instance variables
            inputString = new StringBuilder();
     
            inputField.addKeyListener(this);
            contentPane.add(inputField);
            add(contentPane);
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
     
        }
     
        public static void main(String[] args) {
     
            new TestClass();
     
        }
     
        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void keyTyped(KeyEvent k)
        {
            // GB: to notify that a key has been captured
            System.out.println( "In keyTyped() method." );
     
            int input = k.getKeyChar();
     
            // GB: to display the value of the captured key
            System.out.println( "Input value is (int): " + input );
     
            if (!(Character.isDigit(input) ||
                    (input==KeyEvent.VK_BACK_SPACE) ||
                    (input==KeyEvent.VK_DELETE) ||
                    (input==KeyEvent.VK_DECIMAL) ||
                    (input==KeyEvent.VK_PERIOD)) ||
                    (inputField.getText().contains(".") &&
                            (input==KeyEvent.VK_DECIMAL ||
                            input==KeyEvent.VK_PERIOD))){
                k.consume();
            }
            // GB: to record and display the keys that are recorded 
            else
            {
                inputString.append( "" + (char)input );
                System.out.println( "Recorded input is now: " + inputString );
            }
     
        }
     
    }

  9. The Following 2 Users Say Thank You to GregBrannon For This Useful Post:

    antihero.mc (June 27th, 2014), Norm (June 27th, 2014)

  10. #8
    Junior Member
    Join Date
    Jun 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need help with consuming key events.

    Sorry. Still pretty green. I don't know where you're finding that.

    --- Update ---

    AHHHH ok thank you both.

  11. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    I don't know where you're finding that.
    Can you give some more details on where you are having problems? What is the "that" you refer to?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: need help with consuming key events.

    I don't know where you're finding that.
    Please be specific. I don't know what you're asking or if you're asking at all. I provided links to all but an ASCII table which you can find easily by searching. Or if you mean the details of the getKeyChar() method, refer to the KeyEvent API.

  13. #11
    Junior Member
    Join Date
    Jun 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: need help with consuming key events.

    So it looks like the simplest solution is to just check if the value is equal to "n" (110) and consume it. Thanks again to Norm and Greg.

    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
     
     
    public class TestClass extends JFrame implements KeyListener{
    	private static final long serialVersionUID = 1L;
    	JTextField inputField = new JTextField(20);
    	JPanel contentPane = new JPanel();
     
    //	variable to store accepted inputs
    	StringBuilder inputString;
     
    	public TestClass(){
     
    //		initialize instance variables
    		inputString = new StringBuilder();
     
    		inputField.addKeyListener(this);
    		contentPane.add(inputField);
    		add(contentPane);
    		pack();
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		setVisible(true);
    	}
     
    	public static void main(String[] args) {
     
    		new TestClass();
     
    	}
     
    	public void keyPressed(KeyEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	public void keyReleased(KeyEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	public void keyTyped(KeyEvent k) {
     
    //		notify that a key has been captured
    		System.out.println("In KeyTyped() method.");
     
    		int input = k.getKeyChar();
     
    //		display the value of the captured key
    		System.out.println("Input value is (Int): " + input);
     
    		if(!(Character.isDigit(input) ||
    				input==KeyEvent.VK_BACK_SPACE ||
                    input==KeyEvent.VK_DELETE ||
                    input==KeyEvent.VK_PERIOD) ||
                    (inputField.getText().contains(".") && input==KeyEvent.VK_PERIOD) ||
                    input==110
    				){
    			k.consume();
    		}
     
    //		record and display keys
    		else{
    			inputString.append( "" + (char)input );
    	        System.out.println( "Recorded input is now: " + inputString );
    		}
     
    	}
     
    }
    Last edited by antihero.mc; June 28th, 2014 at 01:31 AM.

  14. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    Try adding a println() statement that prints out the value of input. Then execute the code and press all the keys one at a time to see what is passed to the variable: input. I don't think VK_DECIMAL is ever passed.

    NOTE: Hardcoding 110 in a program without any comments is not a good technique. Better to use 'n'.

    I don't think that code using VK_DECIMAL is needed.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    GregBrannon (June 28th, 2014)

  16. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: need help with consuming key events.

    The formatting of the if statement is hard to understand. Also some comments would make it easier to understand. Here's a rewrite:
                       //  don't consume: digit, backspace, delete or period
    		if (!(Character.isDigit(input) ||
    				(input==KeyEvent.VK_BACK_SPACE) ||
    				(input==KeyEvent.VK_DELETE) ||
    				(input==KeyEvent.VK_PERIOD) ) 
                         // consume . if already have one
                         || (inputField.getText().contains(".")
    			  &&  input==KeyEvent.VK_PERIOD) ) {
    			k.consume();
    		}
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 1
    Last Post: April 3rd, 2014, 02:11 PM
  2. Is programming a very time-consuming process?
    By SOG in forum Totally Off Topic
    Replies: 9
    Last Post: July 16th, 2012, 07:28 AM
  3. [SOLVED] restricting a particular key stroke or key code
    By chronoz13 in forum AWT / Java Swing
    Replies: 2
    Last Post: April 22nd, 2011, 11:19 AM
  4. Exception consuming WebService
    By lzorratto in forum Java ME (Mobile Edition)
    Replies: 0
    Last Post: February 23rd, 2010, 09:13 AM