Aaron
Aaron

Reputation: 11

Rectangular doesnt move through KeyListener

Well, I tried to make rectangular moving while typing arrows on Keyboard. It must work mostly like hitboxes

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;




public class SHOWHITBOX extends JPanel implements KeyListener{

    int move=0;

     
    @Override
    public void keyPressed(KeyEvent e) {
    int key1 = e.getKeyCode();
    if(key1==39){
        move+=10;
        System.out.println(move);
    }
    
    if(key1==37){
        move-=10;
        System.out.println(move);
    }
    
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
    
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }

    
public SHOWHITBOX(){

    
}

public void paintComponent(Graphics gr) {
        gr.drawRect(move,400,1000,100);
        gr.drawRect(move,400,100,100);
        repaint();
    }
}

It doesnt work, however Ive connected it to the class, and it annoys to the button typing (console output). But it still doesnt work. Second rect were did for test

Upvotes: 0

Views: 50

Answers (1)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

There is two problems with your code:

  1. Don't call repaint from paint* method, that would trigger too much unnecessary paint events. Much better is to call repaint at a time where you need the drawing to be made: for example inside methods that modifies the move variable.

  2. You are playing with a panel, so you need some mechanic to give it the focus. If not, it won't be able to receive the keyboard events. I forced the focus from the main requesting it from the window focus.

Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
    
public class ShowHitBox extends JPanel implements KeyListener {
  int move=0;
  @Override
  public void keyPressed(KeyEvent e) {
    int key1 = e.getKeyCode();
    System.out.println(key1);
    if(key1==KeyEvent.VK_R){
      move+=10;
      System.out.println(move);
    }
    
    if(key1==KeyEvent.VK_L){
      move-=10;
      System.out.println(move);
    }
    repaint();
  }

  @Override
  public void keyReleased(KeyEvent arg0) {    
  }

  @Override
  public void keyTyped(KeyEvent arg0) {
  }
    
  public void paintComponent(Graphics gr) {
    super.paintComponent(gr);
    gr.drawRect(move,400,100,100);
  }

  public static void main(String []args) {
    JFrame f = new JFrame("App");
    ShowHitBox hitBox = new ShowHitBox();
    hitBox.addKeyListener(hitBox);
    f.getContentPane().add(hitBox);
    f.setVisible(true);
    hitBox.requestFocusInWindow();
  }    
}

Note that you must call super.paintComponent in your paintComponent and that it is highly recommended to use the virtual keys symbols to test against the inputed keys.

Upvotes: -1

Related Questions