0

I have a class called "DisplayPanel" (which extends JPanel) and I draw a square there that comes from a class called "Square" (which extends JComponent). How to move a rectangle in a JPanel using the keys?

The Square class has the usual painting method:

public void paintComponent(Graphics g) {
    Dimension dimension = getSize();
    super.paintComponent(g);
    Graphics2D graphics2D = (Graphics2D) g;
    g.setColor(Color.black);
    graphics2D.fill(squarishThing); 
}

And the "squarishThing" is a normal rectangle:

Rectangle squarishThing = new Rectangle (0, 0, 50, 50);

The thing is: Unlike "game libraries", trying to do such a thing "manually" is quite confusing. I don't know where the "while loop" goes. I tried to put a KeyListener in the DisplayPanel and I failed miserably to update the rectangle. There's no loop, and I can't repaint the rectangle because the method paintComponent takes that unpleasant argument. OBS: Everytime I try to insert a loop, the software crashes dramatically, so I gave up of doing so.

What can I do to repaint the object according to inputs?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114

1 Answers1

2

can't repaint the rectangle because the method paintComponent takes that unpleasant argument. Never ever call paintComponent, instead use repaint().

Using KeyBindings simply update "squarishThing" to the appropriate value, then call repaint().

Mordechai
  • 15,437
  • 2
  • 41
  • 82