Results 1 to 10 of 10
  1. #1
    Warmonger is offline Member
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Default KeyListeners doesn't work in NB, while MouseListener does

    Well, I'm confused about his one. If theses interfaces work identically, both should be handled easily. But they are not. I'm able to control app using mouse, but KeyPressed() is never called for keyboard.

    Have a look at my code:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package swarmshooter;
    
    import javax.swing.JPanel;
    import java.awt.Component;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import java.awt.Image;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.awt.GraphicsEnvironment;
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsConfiguration;
    import java.awt.Canvas;
    import java.util.Timer;
    import java.awt.Point;
    /**
     *
     * @author Warmonger
     */
    public class Game extends JPanel implements Runnable, MouseListener, KeyListener
    {
        StopGame pause;
        SwarmShooterView parentPanel;
        private Timer timer; //handles threads
        private Thread ticker;
        private boolean running = false;
        Canvas canvas;
        Graphics graphics;
        Graphics2D g2d;
        BufferStrategy buffer;
    
        Color color = Color.BLUE;
    
        private static final int KEY_COUNT = 256;
        private static final int BUTTON_COUNT = 3;
    
        private enum KeyState
        {
            RELEASED, // Not down
            PRESSED, // Down, but not the first time
            ONCE      // Down for the first time
        }
        private enum MouseState
        {
    
            RELEASED, // Not down
            PRESSED, // Down, but not the first time
            ONCE      // Down for the first time
        }
        // Current state of the keyboard
        private boolean[] currentKeys = null;
        // Polled keyboard state
        private KeyState[] keys = null;
    
        // Polled position of the mouse cursor
        private Point mousePos = null;
        // Current position of the mouse cursor
        private Point currentPos = null;
    
        // Current state of mouse buttons
        private boolean[] state = null;
        // Polled mouse buttons
        private MouseState[] poll = null;
    
        Game(SwarmShooterView pp)
        {
            parentPanel = pp;
            pause = new StopGame("Pause");
    
            currentKeys = new boolean[KEY_COUNT];
            keys = new KeyState[KEY_COUNT];
            for (int i = 0; i < KEY_COUNT; ++i)
            {
                keys[i] = KeyState.RELEASED;
            }
            mousePos = new Point(0, 0);
            currentPos = new Point(0, 0);
            // Setup initial button states
            state = new boolean[BUTTON_COUNT];
            poll = new MouseState[BUTTON_COUNT];
            for (int i = 0; i < BUTTON_COUNT; ++i)
            {
                poll[i] = MouseState.RELEASED;
            }
    
            setBounds(GuiHandler.dimension.width, GuiHandler.dimension.height, pp.getX(), pp.getY());
            setMaximumSize(GuiHandler.dimension);
            setMinimumSize(GuiHandler.dimension);
            setPreferredSize(GuiHandler.dimension);
            canvas = new Canvas();
            canvas.setBounds(GuiHandler.dimension.width, GuiHandler.dimension.height, pp.getX(), pp.getY());
            canvas.setIgnoreRepaint( true );
            add(canvas);
            setLayout(null);
            setBackground(GuiHandler.backgroundColor);
    
            graphics = null;
            g2d = null;
        }
    
        public synchronized void start ()
        {
            addMouseListener(this);
            addKeyListener(this);
    
            if (ticker == null || !ticker.isAlive())
                running = true;
            ticker = new Thread(this);
            ticker.setPriority(Thread.MIN_PRIORITY + 1);
            ticker.start();
            setBackground(Color.ORANGE);
    
            timer = new Timer();
            timer.scheduleAtFixedRate(new DrawTimer(this), 0, 30);
            timer.scheduleAtFixedRate(new KeyClearTimer(this), 0, 30);
        }
        
        public void run ()
        {
        }
    
        public synchronized void stop ()
        {
            running = false;
        }
    
        public void init()
        {
            Image offscreenimage = createImage(getMaximumSize().width, getMaximumSize().height);
        }
    
        @Override
        public synchronized void paint(Graphics g)
        {
            g.setColor(color);
            g.fillRect(getX(), getY(), getWidth(), getHeight());
        }
    
        protected void processInput()
        {
            if (buttonDownOnce(2))
            {
                color = Color.BLACK; return;
            }
            if (buttonDownOnce(3))
            {
                color = Color.CYAN; return;
            }
            if (buttonDownOnce(1))
            {
                color = Color.MAGENTA;
                return;
            }
    
            if (keyDown(27))
            {
                System.out.println("Esc - exiting");
                pause.actionPerformed(null);
            }
        }
    
        public synchronized void checkKeys()
        {
            for (int i = 0; i < KEY_COUNT; ++i)
            {
                if (currentKeys[i])
                {
                    if (keys[i] == KeyState.RELEASED)
                    {
                        keys[i] = KeyState.ONCE;
                    }
                    else
                    {
                        keys[i] = KeyState.PRESSED;
                    }
                }
                else
                {
                    keys[i] = KeyState.RELEASED;
                }
            }
    
            mousePos = new Point(currentPos);
            for (int i = 0; i < BUTTON_COUNT; ++i)
            {
                if (state[i])
                {
                    if (poll[i] == MouseState.RELEASED)
                    {
                        poll[i] = MouseState.ONCE;
                    }
                    else
                    {
                        poll[i] = MouseState.PRESSED;
                    }
                }
                else
                {
                    poll[i] = MouseState.RELEASED;
                }
            }
        }
    
        public Point getPosition()
        {
            return mousePos;
        }
    
        public boolean buttonDownOnce(int button)
        {
            return poll[button - 1] == MouseState.ONCE;
        }
    
        public boolean buttonDown(int button)
        {
            return poll[button - 1] == MouseState.ONCE
                    || poll[button - 1] == MouseState.PRESSED;
        }
    
        public synchronized void mousePressed(MouseEvent e)
        {
            System.out.println(e.getButton());
            state[e.getButton() - 1] = true;
        }
    
        public synchronized void mouseReleased(MouseEvent e)
        {
            state[e.getButton() - 1] = false;
        }
    
        public synchronized void mouseEntered(MouseEvent e)
        {
            mouseMoved(e);
        }
    
        public synchronized void mouseExited(MouseEvent e)
        {
            mouseMoved(e);
        }
    
        public synchronized void mouseDragged(MouseEvent e)
        {
            mouseMoved(e);
        }
    
        public synchronized void mouseMoved(MouseEvent e)
        {
            currentPos = e.getPoint();
        }
    
        public synchronized void mouseClicked(MouseEvent e)
        {  //unused
        }
    
       public boolean keyDown(int keyCode)
       {
            return keys[keyCode] == KeyState.ONCE || keys[keyCode] == KeyState.PRESSED;
        }
    
        public boolean keyDownOnce(int keyCode)
        {
            return keys[keyCode] == KeyState.ONCE;
        }
    
        public synchronized void keyPressed(KeyEvent e)
        {
            int keyCode = e.getKeyCode();
            if (keyCode >= 0 && keyCode < KEY_COUNT)
            {
                currentKeys[keyCode] = true;
            }
        }
    
        public synchronized void keyReleased(KeyEvent e)
        {
            int keyCode = e.getKeyCode();
            if (keyCode >= 0 && keyCode < KEY_COUNT)
            {
                currentKeys[keyCode] = false;
            }
        }
    
        public synchronized void keyTyped(KeyEvent e)
        { //not needed
        }
    
        class StopGame extends AbstractAction
        {
            public StopGame(String text)
            {
                super(text);
            }
            public void actionPerformed(ActionEvent e)
            {
               parentPanel.swapView(parentPanel.gamePanel, parentPanel.mainPanel);
               stop();
            }
        }
    }

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    KeyPressed() is never called for keyboard

    Does the component have focus?

  3. #3
    Warmonger is offline Member
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Default

    Not sure. I tried requestFocusInWindow() in various places, just like Start() and before start call, but nothing changed. Thanks for tip, though.

    Also, it should be top visible panel coming from CardLayout.

  4. #4
    asifzbaig is offline Member
    Join Date
    May 2011
    Posts
    56
    Rep Power
    0

    Default

    buddy i think that you surely know that KeyEvent always work only if that prticular key has the focus, or its parent component hs focus.......

    i didn't read youer whole code, so if you have multiple buttons in your GUI and wants to work randomly then go for inputMap() and actionMap()

    Read the document about this at :

    How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    better luck.....

  5. #5
    Warmonger is offline Member
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Default

    I don't have multiple buttons here. Now I'm on separate panel (embedded in CardLayout) which should cover the entire game area and be the only control handler.
    Not sure about the heierarchy of components though.

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

    Default

    Key Bindings could work as noted above. As an aside, what's with all the synchronized methods? That seems very strange to me since this is a Swing app, and those methods should only be called from a single thread, the EDT.

  7. #7
    Warmonger is offline Member
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Default

    setFocusable(true) did the trick :)

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

    Default

    Still, why the synchronized methods? It suggests a possible design issue.

  9. #9
    Warmonger is offline Member
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Default

    At the moment it probably doesn't make much sense as mechanics will be handled by Timer in separate threads.
    But it was just like this in controls example I found on the internet, where Frame performed more additional activities.

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

    Default

    Well, since those methods are all Swing methods and can only be called on one thread, the EDT, I can tell you that there is no reason for them to be synchronized. If so, then there are other problems in the code -- namely some code is making Swing calls off of the EDT, and this can lead to intermittent unpredictable code failure.

Similar Threads

  1. KeyPressed trouble with KeyListeners
    By CuddlyKittens11 in forum Advanced Java
    Replies: 8
    Last Post: 05-28-2011, 10:31 PM
  2. KeyListeners not working
    By superzipzop in forum AWT / Swing
    Replies: 3
    Last Post: 02-06-2011, 04:14 AM
  3. Problem with keylisteners
    By dunafrothint in forum AWT / Swing
    Replies: 2
    Last Post: 11-23-2009, 06:54 PM
  4. [SOLVED] KeyListeners in JavaApplets
    By Unome in forum Java Applets
    Replies: 18
    Last Post: 10-30-2008, 11:36 PM
  5. MouseListener
    By Aswq in forum New To Java
    Replies: 12
    Last Post: 07-18-2008, 09: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
  •