Results 1 to 4 of 4
- 07-18-2011, 05:29 PM #1
Member
- Join Date
- Jul 2011
- Posts
- 42
- Rep Power
- 0
Changing variables in if statements
Hey I'm trying to work out how to make a JLabel move around the screen with the wasd keys.
To do this I'm doing something like this:
int x = 0;
int y = 0;
if (input == 'w') {
y -= 5;
}
else if (input == 'a') {
x -= 5;
}
label.setLocation(x, y);
Only problem is, since I'm changing the value of the x and y variables inside an if statement, its not actually changing the value of the variable outside.
How do I make it do that?
Sorry for the dumb question, bit of a newbie
- 07-18-2011, 05:39 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
- 07-18-2011, 05:57 PM #3
Member
- Join Date
- Jul 2011
- Posts
- 42
- Rep Power
- 0
Hey. I'm sorry I phrased my question very badly and just realized the answer was very obvious. The part of code I posted was actually inside a method and each time I called the method it set the x and y variables to 0.
Sorry for wasting your time, but thanks for the quick reply!
- 07-18-2011, 06:14 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
No need to say sorry; if you defined those variables in a method (they're local to that method then) they're initialized over and over again when that method gets executed. Better define them as member variables (outside of any method) so they can keep their value assigned to them in that method (that's what you want here).
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
if statements for multiple variables
By dookie1293 in forum New To JavaReplies: 9Last Post: 06-17-2011, 09:30 AM -
Changing binding when changing the underlying model object
By ChrisNY in forum NetBeansReplies: 0Last Post: 08-14-2010, 10:09 AM -
if else statements
By sweetpea123 in forum New To JavaReplies: 4Last Post: 04-12-2010, 07:02 PM -
What are Instance variables and static variables?
By sandeshforu in forum New To JavaReplies: 3Last Post: 09-09-2009, 05:48 PM -
Changing color of variables view details
By mtoledo in forum EclipseReplies: 0Last Post: 03-25-2008, 02:35 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks