Hello,

I am unable to register the right key event from this program. Besides setting the focus of JPanel to the KeyListener, I am not sure what else can be done. I will be grateful for any help.

Thank you!

import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.*;
import javax.swing.*;


public class Board extends JPanel 
{
    private int x = 20, y = 20;
    private boolean flag = true;

    public Board() 
    {

        setFocusable(true); 

        addKeyListener(

                new KeyAdapter()
                {
                   public void keyPressed(KeyEvent e) 
                   {
                        if (e.getKeyCode() == KeyEvent.VK_RIGHT ) 
                        {
                                flag = false;
                                repaint();
                        } 

                   }
                }
           );       

    }


    public void paintComponent(Graphics g) 
    {
           if (flag)
            {
                  g.setColor (Color.BLUE);
                  g.fillRect (x + 10, y, 20, 20);
            }

           else
              {
                    g.setColor (Color.RED);
                    g.fillRect (x + 100, y, 20, 20);
              }

    }       


    public static void main(String[] args) {

        JFrame f = new JFrame();
        Board test = new Board();
        test.requestFocus();
        f.add(test);
        f.setSize(600,600);
        f.setVisible(true);
    }
}

Is the keyPressed() method ever called?

unable to register the right key event from this program

Can you explain what "to register" means? What do you want the code to do? What does the code do now?

Hello,

NormR1:
I want the program to draw a rectangle at a new location (as specified in the program) when the right arrow key is pressed. Currently, it does nothing.

James:
Thank you! I will look into KeyBindings.

Currently, it does nothing.

Is the listener called? What does it do when it is called?

want the program to draw a rectangle at a new location

Where is the value of the location changed?

What will the user see when the code is executed and the arrow pressed?
The program starts showing a blue square. When the -> arrow is pressed a red square is drawn.

Hello NormR1,

It works now. I removed the KeyAdapter and reverted back to KeyListener and added the KeyReleased(KeyEvent) and KeyTyped(KeyEvent) methods, which are empty.

Thank you!

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.