GeeCON Prague 2014*
The moose likes Swing / AWT / SWT and the fly likes using JFrame with KeyListener Interface and using paint method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "using JFrame with KeyListener Interface and using paint method" Watch "using JFrame with KeyListener Interface and using paint method" New topic
Author

using JFrame with KeyListener Interface and using paint method

Raviteja Penki
Greenhorn

Joined: Oct 27, 2011
Posts: 19
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

Joined: Oct 27, 2011
Posts: 19
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

Joined: Oct 27, 2005
Posts: 19697
    
  20

I'll move this to our GUI forum. And please UseCodeTags next time.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2191
    
    7
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

Joined: Oct 16, 2003
Posts: 1084
    
  10

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.


Ranga.
SCJP 1.4, OCMJEA/SCEA 5.0.
 
GeeCON Prague 2014
 
subject: using JFrame with KeyListener Interface and using paint method