0
\$\begingroup\$
public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Character c = new Character();
        frame.add(c);

        frame.setSize(600, 600);
        frame.setTitle("Keyboard control");
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

character class

public class Character extends JPanel implements KeyListener{

   int posx = 0, posy = 0;

   public void movementX(int i) {
        posx+=i;
    }
   public void movementY(int i) {
       posy+=i;
   }

       public void paint() {
           repaint();
       }

     public void paintComponent(Graphics g) {
        super.paintComponent(g);

        this.setBackground(new Color(0, 0, 0));

        g.setColor(new Color(0, 0, 255));
        g.fillRoundRect(posx, posy, 50, 50, 4, 4);

    }


    public void keyPressed(KeyEvent e) {
        movementX(10);
        paint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}
\$\endgroup\$
1

1 Answer 1

1
\$\begingroup\$

well, simple you are implementing KeyListener but you are never attaching that to the panel, also you must focus your component to be able to listen for events, here you can have a more explained response:

https://stackoverflow.com/questions/9333876/how-to-simply-implement-a-keylistener?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .