Results 1 to 7 of 7
Thread: Problem with scope
- 07-16-2011, 12:23 AM #1
Problem with scope
I need help with a scope problem. Here is my code.
Ok well I want to move the p1 object with a keyPressed event. It compiles but it seems to be out of scope. Any way on how to fix this?Java Code:public class someClass implements KeyListener { int px = 300; int py = 200; Player p1 = new Player(); public someClass () { // Jframe made here jframe.add(p1); p1.setBounds(px, py, 45, 50); } public void keyPressed (KeyEvent e) { px += 50; p1.setBounds(px, py, 45, 50); } }
Note: I know this isn't valid code, but I just want to get the idea across.Last edited by jlennards; 07-16-2011 at 12:27 AM.
-
What do you mean by "it seems to be out of scope"? There are no scope issues in the code posted.
- 07-16-2011, 12:29 AM #3
When I call the Method with the keypressed event, the object dosen't move.
By habit I blame scope.
-
It's not really a scope issue but likely a reference issue or a focus issue. For a KeyListener to work, the component it is listening to must have focus. You can check to see if your key listener is active by adding some System.out.println statements in it and see if they print. If the KeyListener is working well, then again your issue could be one of reference -- that you're moving a Player object, but just not the currently visualized Player object. Understand that every time you call new Player(), you are creating a new and distinct Player object. If you want this class to act on a Player object that has been created elsewhere, you'll need to pass a reference of that Player object into this class, perhaps as the parameter of a setPlayer method.
- 07-16-2011, 04:03 AM #5
-
Last edited by Fubarable; 07-16-2011 at 04:35 AM.
- 07-16-2011, 04:32 AM #7
Similar Threads
-
ArrayList going out of scope
By meustace in forum New To JavaReplies: 2Last Post: 05-20-2010, 01:14 AM -
Scope Problem???
By c_walker in forum New To JavaReplies: 4Last Post: 12-12-2009, 02:30 AM -
Problem with Session Scope while using with Java Bean
By sulthanmytheen in forum JavaServer Pages (JSP) and JSTLReplies: 0Last Post: 03-27-2009, 10:50 AM -
[SOLVED] scope problem with a servlet
By pnolans in forum Java ServletReplies: 7Last Post: 08-23-2008, 02:50 PM -
return out of scope?
By another_steve in forum New To JavaReplies: 5Last Post: 01-28-2008, 09:34 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks