Wednesday 15 September 2010

java - Moving a rectangle in JPanel with arrow keys using KeyListener -


I am trying to create a JPanel with arrow keys. It does not work, I believe that this is my internal class which increases the KeyAdapter I'm not even sure that ActionListener was implemented The square I have created does not matter because it is just the frame

  package, JerryWorld; Import javax.swing *; Import java.awt. *; Import java.awt.event. *; Public class Jerry JPLNL applies ActionListener {int SizeX, SizeY, PosX, Posy, Velx, Vely; Image image; Timer time = new timer (1, this); Public Jerry () {Image I = New Immune (); AddKeyListener (new AL ()); Time.start (); Img = i.getImage (); PosX = 375; Posy = 250; } Public Zero Color (Graphics G) {Graphics2D g2d = (Graphics2D) G; G2d.fillRect (PosX, Posy, 50, 100); } Public Zero Functionality (ActionEvent e) {PosX = PosX + Velx; Repaint (); } Private class provides AL KeyAdapter {public zero keypress (KeyEvent e) {int key = e.getKeyCode (); Println ("yay!"); If (key == KeyEvent.VK_LEFT) VelX = -1; Else if (key == KeyEvent.VK_RIGHT) Wells = 1; } Public Zero Key Relayed (Key Event E) {int key = e.getKeyCode (); If (key == KeyEvent.VK_LEFT) Wells = 0; Else if (key == KeyEvent.VK_RIGHT) VelX = 0; }}}    

  • You want to search this site for similar questions , As they usually get the same issue and the same answer.
  • They will tell you that the focus is a problem because the keygenist of a component will not work until it has its focus.
  • Whether you want to use KeyListener at all but not in key binding.
  • They will tell you that paint (...) rather than paintComponent (...) unless you are sure that you Want to override component boundaries and children's painting (you do not).
  • They can give you super method paintComponent (...) .

    Also see it inside

No comments:

Post a Comment