• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using JFrame with KeyListener Interface and using paint method

 
Raviteja Penki
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

i am trying to write a program
aim: generate an image by extending JFrame and by implementing KeyListener
i want to change the position of the image by pressing the keys -,=
i am unable to get the output.

verify this once and tell me the root cause

here i am attaching the code

 
Raviteja Penki
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
its only printing the - pressed or = pressed
but its not doing any graphical thing on the JFrame window like changing the back ground color moving the image to that positions
not even printing the string
 
Rob Spoor
Sheriff
Pie
Posts: 20613
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll move this to our GUI forum. And please UseCodeTags next time.
 
Rob Camick
Ranch Hand
Posts: 2613
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use KeyListeners. They only work when the component has focus. Intead you should be using Key Bindings.

Don't override the paint() method of a JFrame. Instead read the section from the Swing tutorial on Custom Painting for the proper way to do this.
 
Ranganathan Kaliyur Mannar
Bartender
Posts: 1101
10
Java Netbeans IDE Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you are storing the Graphics object and making changes to that from the keyListener methods. I am not sure if the same graphics object is passed to the paint methods. Instead, you can store the key event generated in an instance variable (in the key listener methods) and make a call to repaint(). Then in the paintComponent method, you have to do the if/switch check and draw the graph accordingly.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic