get user input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • game2d
    New Member
    • Apr 2013
    • 59

    get user input

    i am having two problems. 1st is i want to print 3 char from string. i dont want to print ontop of each other so i am doing 600*i. but this not really working.
    Code:
    g.drawString(username[i], 600*i, 300);
    2nd question is that if user hit 3 keys at same time than in string it will add only one and string will be full. bc user hit 3 times at same time.


    full code
    Code:
    //paint method
    for(int i = 0; i < username.length; i++){
    	g.drawString(username[i], 600*i, 300);
    	System.out.print(username[i]);
    }

    Code:
    int z = 0;
    String username[] = new String[3];
    
    public void keyPressed(KeyEvent e)
        {
            int keys = e.getKeyCode();
    
            username[z] = KeyEvent.getKeyText(keys);
            e.consume();                  
        }
    
    public void keyReleased(KeyEvent e)
    { 
        int keys = e.getKeyCode();
    
        z++;
        e.consume(); 
    }
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    OK, I'm a little confused...
    1. You say you want to print characters from Strings, but it looks like you're printing whole Strings. From what you say I'd imagine something like:
      Code:
      char[] username = {' ',' ',' '};
      public void paint(...) {
        //...
        for(int i=0; i<username.length(); i++) {
          g.drawString("" + username[i], 600*i, 300);
          System.out.print(username[i]);
        }
        //...
      }
      or maybe
      Code:
      String username = "";
      public void paint(...) {
        //...
        for(int i=0; i<username.size(); i++) {
          g.drawString("" + username.get(i), 600*i, 300);
          System.out.print(username.get(i));
        }
        //...
      }
      or even
      Code:
      String username = "";
      public void paint(...) {
        //...
        g.drawString(username.substring(0,3), 600, 300);
        System.out.print(username.substring(0,3));
        //...
      }
    2. What you could try is synchronizing the keyPressed function; I don't know whether this will work, but it's something you could try. This also means, that an array is no longer an option unless you synchronize that manually; switching to a synchronized collection, e.g. a synchronized ArrayList, is probably the best solution. This is what that would look like:
      Code:
      List username = Collections.synchronizedList(new ArrayList());
      
      public synchronized void keyPressed(KeyEvent e) {
        int keys = e.getKeyCode();
        username.add(KeyEvent.getKeyText(keys));
        e.consume();
      }
      If that doesn't work you may want to have a look at Key Bindings.

    Does that help?

    Comment

    Working...