This is the code of my key listener for a game.The keys move a plank upwards and downwards for two players.The problem is when one player keeps a key pressed then the other key event does not execute.what i want to do is that both players should be able to move their planks simultaneously.

private class MyKeyBoardListner implements KeyListener
    {
        boolean flag=true;
        public void keyPressed(KeyEvent ke)
        {

    //    System.out.println(ke.getKeyCode());

        if(ke.getKeyCode()==10||ke.getKeyCode()==27)
        {

            if(flag==false)        //pause logic with ESC and return key
            {ba.t.suspend();
        flag=!flag;
            }
            else if(flag==true)
            {        ba.t.resume();
                    flag=!flag;
            }
        }
        if(flag==false)//if paused key events wont work
        {

                    if(ke.getKeyCode()==83)
            {

                    System.out.println(ke.getKeyCode());
                    if(dr.y+100<=dr.getHeight())
                dr.y=dr.y+40;

            else if(dr.y+15<dr.getHeight())
                 dr.y=dr.y+15;
        dr.repaint(plank1);

            }
                if(ke.getKeyCode()==87)
            {
                    System.out.println(ke.getKeyCode());
                    if(dr.y-40>=0)
                dr.y=dr.y-40;
                dr.repaint(plank1);

            }
                if(ke.getKeyCode()==40)
            {

                    System.out.println(ke.getKeyCode());
                    if(dr.w+100<=dr.getHeight())
                dr.w=dr.w+40;
                    else if(dr.w+15<=dr.getHeight())
                        dr.w=dr.w+15;

            dr.repaint(plank2);

            }
                if(ke.getKeyCode()==38)
            {
                    System.out.println(ke.getKeyCode());
                    if(dr.w-40>=0)
                dr.w=dr.w-40;
            dr.repaint(plank2);

            }

        }
        }

problem is when one player keeps a key pressed then the other key event does not execute

Is there a referee that could prevent one player from cheating?

What is the flow of events to the key listener? Are there only event coming from the pressed key until that key is released? If so, the controls would be at the OS level.

If you are getting events from both keys you could restrict the time between handling key presses on a single key by requiring a minimum time between presses by using the System.currentTimeMillis() values.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.