• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

using JFrame with KeyListener Interface and using paint method

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll move this to our GUI forum. And please UseCodeTags next time.
 
Rancher
Posts: 3324
32
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1104
10
Netbeans IDE Java Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic