Recommendations:
- You don't call paint or paintComponent directly.
- Having the paintComponent in another class will do nothing of use for you.
- If you want to move the rectangle that you draw, don't use hard-coded numbers. Use fields that can be changed. So rather than
g.drawRect(250, 250, 10, 10);
, haveg.drawRect(rectX, rectY, rectW, rectH);
. Edit, As you yourself suggest,"I was thinking on drawing a rectangle using variables and at keyevent modify that variables but I dont know if thats the correct way to do it."
- Give the painting JPanel class these fields plus public setter methods that will allow other classes the ability to change the field states, and then call repaint. i.e,
setRectX(int rectX)
,setRectY(int rectY)
, etc... - Calling repaint on the drawing JPanl will usually trigger the painting mechanisms to initiate a painting sequence, and this will call (indirectly) the JPanel's paintComponent method.
- Don't use a KeyListener if you can avoid it, but rather use Key Bindings. For an example program on use of these, please have a look here.