Results 1 to 17 of 17
  1. #1
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default Help: adding keylistener to a thread

    Hi everyone, I'm working on a simple Java applet program. By default, the program will let a rectangle move from left to right in a continuous process. I implemented this feature by using a thread. What I want to do is: when the rectangle is moving from left to right, the program can receive the keyboard input and change the variable "active" and then let the rectangle change its moving direction to from up to down. My problem is I don't know how to add the keylistener to the program. Below (also attachment) is the existing code. Thanks in advance for your help!


    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package test;
    
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    /**
     *
     * 
     */
    public class TestJPanel extends JPanel implements Runnable{
        private boolean active;
        private Rectangle rect;
        public TestJPanel()
        {
            super();
            this.rect = new Rectangle( 100, 100, 50, 100);
            this.active = false;
            this.setFocusable( true);
            return;
        }
        
        @Override
        public void paint( Graphics g)
        {
            super.paint(g);
            g.drawRect( this.rect.x, this.rect.y, this.rect.width, this.rect.height);
            return;
        }
        
        public void start()
        {
            Thread thread = new Thread( this);
            thread.start();
        }
        
        @Override
        public void run()
        {   
            for (int i = 0; i < 100; i++) {
                this.move();
                this.repaint();
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        public void move() 
        {
            if( this.active == false)
                this.rect.setLocation( this.rect.x + 2, this.rect.y);
            else
                this.rect.setLocation( this.rect.x, this.rect.y + 2);
            return;
        }
    }
    Attached Files Attached Files
    Last edited by Hooiser; 07-26-2011 at 06:01 PM. Reason: change code format

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Please post your code in the forum. Be sure to wrap it in code tags. Use the # icon above the input box.

    You add a listener to a component by creating a class that implements the listener, creating an instance of that class and calling the components add....Listener method with that instance as an argument.

    Do a Search here on the forum for the type of listener you are working with for code samples.

  3. #3
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Thanks for your reply! I have changed the code format.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Next you are you going to try adding the listener?

  5. #5
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    I tried the KeyListener, here are the codes I wrote:
    KeyListener:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package test;
    import java.awt.event.*;
    /**
     *
     *
     */
    public class InputListener implements KeyListener{
        TestJPanel testJPanel;
        public InputListener( TestJPanel testJPanel)
        {
            super();
            this.testJPanel = testJPanel;
            return;
        }
        
        @Override
        public void keyPressed( KeyEvent e)
        {
            System.out.println("pressed");
            this.testJPanel.setActive( true);
            return;
        }
        
        @Override
        public void keyReleased( KeyEvent e)
        {
            System.out.println("released");
        }
        
        @Override
        public void keyTyped( KeyEvent e)
        {
            
        }
    }

    Now, add the InputListener to TestJPanel, and TestJPanel becomes:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package test;
    
    import java.awt.*;
    import javax.swing.*;
    /**
     *
     *
     */
    public class TestJPanel extends JPanel implements Runnable{
        public boolean active;
        private Rectangle rect;
        public TestJPanel()
        {
            super();
            this.rect = new Rectangle( 100, 100, 50, 100);
            this.active = false;
            this.setFocusable( true);
            InputListener listener = new InputListener( this);
            this.addKeyListener( listener);
            return;
        }
        
        @Override
        public void paint( Graphics g)
        {
            super.paint(g);
            g.drawRect( this.rect.x, this.rect.y, this.rect.width, this.rect.height);
            return;
        }
        
        public void start()
        {
            Thread thread = new Thread( this);
            thread.start();
        }
        
        @Override
        public void run()
        {   
            for (int i = 0; i < 100; i++) {
                this.move();
                this.repaint();
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        public void move() 
        {
            if( this.active == false)
                this.rect.setLocation( this.rect.x + 2, this.rect.y);
            else
                this.rect.setLocation( this.rect.x, this.rect.y + 2);
            return;
        }
        
        public void setActive( boolean active)
        {
            this.active = active;
            return;
        }
    }
    When I ran the code, when the rectangle was moving from left to right, I input from the keyboard, then, there was nothing happened. I even didn't get the message "pressed" from InputListener.keyPressed( KeyEvent e). Which part do you think I was missing? Thanks!

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    You haven't posted the code that tests your classes.
    How are you testing them?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You set the JPanel as focusable, but you may need to request focus in window, though I'm not 100% sure on this. Also, don't override the JPanel's paint method but rather it's paintComponent method. And call super.paintComponent as the first method call of your override.

  8. #8
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    I'm using NetBeans. Most of the codes are generated by NetBeans to create a user interface. I add a line in function "void jButton1ActionPerformed()" to call "TestJPanel.start()"


    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * TestJApplet.java
     *
     * Created on Jul 26, 2011, 12:56:12 PM
     */
    package test;
    
    /**
     *
     * @author
     */
    public class TestJApplet extends javax.swing.JApplet {
    
        /** Initializes the applet TestJApplet */
        public void init() {
            try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
    
                    public void run() {
                        initComponents();
                    }
                });
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
        //below is generated by NetBeans
        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            jPanel1 = new TestJPanel();
            jPanel2 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
    
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Paint Panel", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 638, Short.MAX_VALUE)
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 452, Short.MAX_VALUE)
            );
    
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Control Panel", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
    
            jButton1.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton1)
                    .addContainerGap(104, Short.MAX_VALUE))
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton1)
                    .addContainerGap(418, Short.MAX_VALUE))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
        }// </editor-fold>                        
    
        //here I called TestJPanel.start() to start the thread
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            this.jPanel1.start();
            return;
        }                                        
    
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private TestJPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        // End of variables declaration                   
    }

  9. #9
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Thanks for your reply, Fubarable! If I need to request focus in window, what should I do? In the thread I replied to Norm, I posted the code for JFrame. Please let me know which code should I add to the JFrame.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    I get messages printed and the box moving when I execute it in AppletViewer.

  11. #11
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    I get messages printed and the box moving when I execute it in AppletViewer.
    Did you input from keyboard before pressing the "start" button? Or you pressed the "start" button and then input from the keyboard? My situation is: before pressing the "start" button, I can get messages printed and the keylistener works properly. But If I press the "start" button firstly, then the keylistener cannot listen any input from keyboard.

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Try adding a FocusListener to the panel and see what happens.

  13. #13
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Try adding a FocusListener to the panel and see what happens.
    Hi Norm, I tried adding a FocusListener to TestJPanel. The FocusListener looks like this:

    Java Code:
    package test;
    import java.awt.event.*;
    /**
     *
     *
     */
    public class InputFocusListener implements FocusListener{
        
        @Override
        public void focusGained( FocusEvent e)
        {
            System.out.println("focus gained");
        }
        
        @Override
        public void focusLost( FocusEvent e)
        {
            System.out.println("focus lost");
        }
    }
    When I start the applet, "focus gained" will be shown on the console. The keylistener works fine at that time. However, if I pressed the start button, the "focus lost" will be shown and the keylistener will not work anymore.

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    the "focus lost" will be shown and the keylistener will not work anymore.
    If a component loses focus, how can you give it back?

    Who has focus when you press the button? The display shows it.
    You can Press the Tab key to move the focus.

  15. #15
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    If a component loses focus, how can you give it back?

    Who has focus when you press the button? The display shows it.
    You can Press the Tab key to move the focus.
    By setting other components not focusable, it works fine now! Thanks a lot for you help!

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Another way could be to request focus. See post#7

  17. #17
    Hooiser is offline Member
    Join Date
    Jul 2011
    Location
    Bloomington, IN
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Another way could be to request focus. See post#7
    Thanks, great help to me!

Similar Threads

  1. Adding keyListener to a 2D object.
    By Guy in forum New To Java
    Replies: 2
    Last Post: 07-24-2011, 08:20 PM
  2. adding keylistener
    By natdizzle in forum AWT / Swing
    Replies: 2
    Last Post: 02-02-2011, 01:22 AM
  3. Help adding a keylistener to a paint class
    By Phill Phan in forum New To Java
    Replies: 3
    Last Post: 01-20-2011, 09:28 PM
  4. Adding a KeyListener to a JFrame with buttons.
    By jamhead in forum AWT / Swing
    Replies: 1
    Last Post: 12-11-2010, 07:29 PM
  5. Help me in adding keylistener
    By kumarv75 in forum CLDC and MIDP
    Replies: 0
    Last Post: 06-22-2010, 07:10 AM

Posting Permissions

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