Results 1 to 13 of 13
  1. #1
    JDHoward is offline Member
    Join Date
    Mar 2014
    Posts
    4
    Rep Power
    0

    Default Trouble with accessing my keylistener from my thread.

    I start my thread, it's for a real basic game I'm learning. Everything was working fine, until I got to recognizing keys. It runs, and I can close using the mouse on the close command, but the keys aren't being generated from the keyboard. I copied it to a working sample, and here are the two files.

    package testkeys;

    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferInt;
    import javax.swing.JFrame;
    import testkeys.input.Keyboard;

    /**
    *
    * @author John TestKeys.java
    */
    public class TestKeys extends Canvas implements Runnable {

    /**
    * @param args the command line arguments
    */
    public boolean keypress = false;

    private Keyboard key;
    private Thread thread;
    private JFrame frame;

    public TestKeys (){

    Dimension size = new Dimension ( 300, 160);
    setPreferredSize(size);

    frame = new JFrame();

    key = new Keyboard();

    addKeyListener(key);
    }

    public synchronized void start (){
    thread = new Thread(this, "Display");

    thread.start();
    }
    public void run () {
    do {
    keypress = key.checkkeys();
    }while(keypress == false);

    }
    public static void main(String[] args) {
    // TODO code application logic here

    TestKeys test = new TestKeys();

    test.frame.add(test);
    test.frame.pack();
    test.frame.setDefaultCloseOperation(JFrame.EXIT_ON _CLOSE);
    test.frame.setVisible(true);

    test.start();
    }

    }


    package testkeys.input;

    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    /**
    *
    * @author John
    */

    public class Keyboard implements KeyListener {

    private boolean keys[] = new boolean[120];

    public boolean checkkeys () {

    for ( int i=0; i < keys.length; i++){
    if (keys[i]){
    System.out.println("Key: " + i);
    return true;
    }
    }
    return false;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
    }

    }

    The idea was to set the return value to true if any key is pressed, thus quitting, for this short sample program. Problem, it never recognizes any keys pressed on the keyboard. New to java and threading.

    Any help appreciated.

    John

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,321
    Rep Power
    25

    Default Re: Trouble with accessing my keylistener from my thread.

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JDHoward is offline Member
    Join Date
    Mar 2014
    Posts
    4
    Rep Power
    0

    Default Re: Trouble with accessing my keylistener from my thread.

    Quote Originally Posted by Norm View Post
    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    Sorry, here it is again:

    Java Code:
    package testkeys;
    
    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferInt;
    import javax.swing.JFrame;
    import testkeys.input.Keyboard;
    
    /**
     *
     * @author John
     */
    public class TestKeys extends Canvas implements Runnable {
    
        /**
         * @param args the command line arguments
         */
        public boolean keypress = false;
        
        private Keyboard key;
        private Thread thread;
        private JFrame frame;
        
        public TestKeys (){
            
            Dimension size = new Dimension ( 300, 160);
            setPreferredSize(size);
            
            frame = new JFrame();
            
            key = new Keyboard();
            
            addKeyListener(key);
        }
    
        public synchronized void start (){
            thread = new Thread(this, "Display");
            
            thread.start();
        }
        public void run () {
            do {
                keypress = key.checkkeys();
            }while(keypress == false);
              
        }
        public static void main(String[] args) {
            // TODO code application logic here
            
            TestKeys test = new TestKeys();
            
            test.frame.add(test);
            test.frame.pack();
            test.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            test.frame.setVisible(true);
            
            test.start();
        }
        
    }
    Then the second file is:

    Java Code:
    package testkeys.input;
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    /**
     *
     * @author John
     */
    
    public class Keyboard implements KeyListener {
    
        private boolean keys[] = new boolean[120];
        
        public boolean checkkeys () {
            
            for ( int i=0; i < keys.length; i++){
             if (keys[i]){
                System.out.println("Key: " + i);
                return true;
             }
            }
            return false;
        }
        
        @Override
        public void keyTyped(KeyEvent e) {
        
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            keys[e.getKeyCode()] = true;
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            keys[e.getKeyCode()] = false;
        }
        
    }
    Better?

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,525
    Rep Power
    5

    Default Re: Trouble with accessing my keylistener from my thread.

    Not certain what you are trying to do with your keylistener or why you are using a thread. In any event, you set your key value to true. Then your thread checks to see if any keys are true and if so it returns. Try putting some print statement in your listener methods to see the behavior.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,321
    Rep Power
    25

    Default Re: Trouble with accessing my keylistener from my thread.

    Make sure the GUI component has the focus.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Trouble with accessing my keylistener from my thread.

    It's not properly synchronized, so the thread might never see the changes to the boolean values. See the section titled "visibility" on this page: Synchronization and the Java Memory Model
    Get in the habit of using standard Java naming conventions!

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,525
    Rep Power
    5

    Default Re: Trouble with accessing my keylistener from my thread.

    Actually, it appears to work as written. It's just his general logic is probably incorrect (depending on what he wants to do). Sync may be another problem though. The OP needs to answer the questions posed.

    Regards,
    Jim
    Last edited by jim829; 03-24-2014 at 07:35 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    JDHoward is offline Member
    Join Date
    Mar 2014
    Posts
    4
    Rep Power
    0

    Default Second post, kinda

    I posted this in multithread, but they seemed to feel I didn't really need to use threads at all. It's a rather beginning question, so thought I would try posting here. The basic problem is, I took this code from a game I was working on, because I can't get the key generator to work, meaning its not reading keys from the keyboard. It runs and all, but every time I press a key, it is supposed to print that key number and quit. What am I doing wrong when calling keylistener?

    Java Code:
    package testkeys;
    
    import java.awt.Canvas;
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import testkeys.input.Keyboard;
    
    /**
     *
     * @author John
     */
    public class TestKeys extends Canvas {
    
        /**
         * @param args the command line arguments
         */
        public boolean keypress = false;
        
        private Keyboard key;
        private Thread thread;
        private JFrame frame;
        
        public TestKeys (){
            
            Dimension size = new Dimension ( 300, 160);
            setPreferredSize(size);
            
            frame = new JFrame();
            
        }
    
        public void run () {
            
            key = new Keyboard();
            addKeyListener(key);
            
            do {
                keypress = key.checkkeys();
            }while(keypress == false);
            System.exit(0);
        }
        
        public static void main(String[] args) {
            // TODO code application logic here
            
            TestKeys test = new TestKeys();
            
            test.frame.add(test);
            test.frame.pack();
            test.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            test.frame.setVisible(true);
            
            test.run();
        }
        
    }
    Second .java source.

    Java Code:
    package testkeys.input;
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    /**
     *
     * @author John
     */
    
    public class Keyboard implements KeyListener {
    
        public boolean keys[] = new boolean[120];
        
        public boolean checkkeys () {
            
            keys[119] = true;
            
            for ( int i=0; i < keys.length; i++){
             if (keys[i]){
                System.out.println("Key: " + i);
                return true;
             }
            }
            return false;
        }
        
        @Override
        public void keyTyped(KeyEvent e) {
        
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            keys[e.getKeyCode()] = true;
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            keys[e.getKeyCode()] = false;
        }
        
    }
    Thanks in advance for any help. They mentioned focus of the window, but if it is in the forefront, I thought it automatically had focus. I just need the code to acknowledge a key has been pressed, in my case to move a graphic on the window, for the eventual game. Like I said, new to Java, but long time programmer, just rusty. Been an admin <please, no hisses>.

    John

  9. #9
    JDHoward is offline Member
    Join Date
    Mar 2014
    Posts
    4
    Rep Power
    0

    Default Re: Trouble with accessing my keylistener from my thread.

    Thanks for the responses, my guess is both the sync problems and focus are correct. I stopped using sync, and switched it around some to just a straight program and put it in New Java, probably should have posted there to begin with. I was wanting to use threads since at one point, I was going to attempt and create multiple threads for multiplayer. Looking to far down the road, as always.

    Thanks again,

    John

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,321
    Rep Power
    25

    Default Re: Trouble with accessing my keylistener from my thread.

    Threads merged.
    I thought it automatically had focus
    Not necessarily. You need to request focus for some components.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,525
    Rep Power
    5

    Default Re: Trouble with accessing my keylistener from my thread.

    Just click your mouse in the JFrame to get the focus. In this case, that's all I did. And as I said earlier, threads are not necessary but they will be used behind the scenes to process your key events. And I am still not certain why you are using checkkeys() and an array of 120.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,321
    Rep Power
    25

    Default Re: Trouble with accessing my keylistener from my thread.

    an array of 120.
    One for each keyCode
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,525
    Rep Power
    5

    Default Re: Trouble with accessing my keylistener from my thread.

    I understand that part. But then in the original post, when he pressed the key, the array element is set to true so the loop returns true. So then checkkeys returns true and the thread exits. Now that the OP sets element 119 to true, the thread exits immediately. Perhaps that is a test. In any event I was wondering why he wanted to use an array of 120? It isn't needed to do what the OP is doing.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. KeyListener
    By tim8w in forum AWT / Swing
    Replies: 1
    Last Post: 01-28-2013, 07:57 PM
  2. Trouble with Thread.sleep
    By atomant in forum New To Java
    Replies: 3
    Last Post: 05-16-2012, 08:45 PM
  3. Replies: 5
    Last Post: 12-18-2011, 04:06 AM
  4. Help: adding keylistener to a thread
    By Hooiser in forum Threads and Synchronization
    Replies: 16
    Last Post: 07-26-2011, 10:17 PM
  5. VJSF/Tomcat6.x: Trouble accessing libraries
    By VJSFDeveloper in forum SWT / JFace
    Replies: 0
    Last Post: 09-08-2008, 04:52 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •