0

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

camickr
  • 321,443
  • 19
  • 166
  • 288
Aaron
  • 11
  • `repaint` must be called to initiate the painting, thus when you modify `move`. Don't call `repaint()` inside `paintComponent` but inside `keyPressed` (preferably at the end of). – Jean-Baptiste Yunès Jul 05 '23 at 11:30
  • Tried. Doesnt work – Aaron Jul 05 '23 at 11:35
  • 2
    **posted** code, moving `repaint()` and including call to `super.paintComponent()`, is working *perfectly* for me - please include a [mre] || are you seeing any output (from `println`) or is the `SHOWHITBOX` even not `set Focusable` (its default)? – user16320675 Jul 05 '23 at 12:17
  • Yes, output number gets bigger while pressing button. But, even with setFocusable, even with superPaintComp it doesnt work – Aaron Jul 05 '23 at 12:51
  • ***Again***, please read or re-read the [mre] link and then try to create and post one of these in your question. Otherwise, you're forcing everyone to try to guess why code not shown is not working, not a worthwhile endeavor. – Hovercraft Full Of Eels Jul 05 '23 at 13:06
  • Class names should only have the first letter of the word capitalized: "ShowHitBox". Learn and follow Java naming conventions. Following conventions of the API is a good way to learn. – camickr Jul 05 '23 at 14:46

1 Answers1

-1

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.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • 1
    `super.repaintComponent`? and `repaintComponent`? Are you sure about these terms? And why recommend giving the JPanel focus and that the original poster continue to use a KeyListener, which often requires kludges to be useful when it is almost always better to use Key Bindings rather than a KeyListener, and in this very situation, it is most definitely better to use Key Bindings? – Hovercraft Full Of Eels Jul 05 '23 at 17:55
  • (1-) for forcing the user to use the mouse to give focus to the panel. How does the user know this is needed? The keys should just work without the need for the mouse, which is why Key Bindings should be used since they can handle the key events whether the component does or doesn't have focus. Also if you read the API for requestFocus() focus it will indicate you should be using `requestFocusInWindow()`. Finally you can only request focus on a visible component in a visible frame. The frame is not yet visible when you invoke the statement so it just happens to work – camickr Jul 05 '23 at 17:58
  • Myself, for smoother drawing, I would use Key Bindings that triggered a Swing Timer to start and stop when a key is pressed. [For example](https://stackoverflow.com/a/6887354/) – Hovercraft Full Of Eels Jul 05 '23 at 18:00
  • @camickr corrected. – Jean-Baptiste Yunès Jul 06 '23 at 06:20
  • @user16320675 triggering paint events in paint* methods is bad. – Jean-Baptiste Yunès Jul 06 '23 at 06:21
  • @HovercraftFullOfEels OP did say anything about smooth moves... He said keystroke => move, that all. Isn't it? – Jean-Baptiste Yunès Jul 06 '23 at 06:24
  • 1
    I am aware that "*triggering paint events in paint\* methods is bad*" - I never stated something else. Your first point, as posted "*You need to call repaint when you need to see the drawings*" - is not the problem of the code in the question (because `repaint` **is** already being called, even if from a "*bad*" location) - it being "*bad*" is also the reason why I wrote "too often" in my previous comment – user16320675 Jul 06 '23 at 06:28
  • @user16320675 oh I see what you exactly mean now. Right. – Jean-Baptiste Yunès Jul 06 '23 at 06:30
  • 1
    (just to avoid *confusion* by OP or someone else reading this answer) – user16320675 Jul 06 '23 at 06:33