1

I'm making a pong game in java and can't figure out how to pause and have a watch watching if you click the pause button:

fileItem5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
psd = true;

but I can't access it from my other classes. I declared it as

public boolean psd;

but when I enter it on my second class it gives me a "variable needs to be static error".

Govind Balaji
  • 639
  • 6
  • 17
user1979117
  • 29
  • 2
  • 8

2 Answers2

2

forget Singletons, better is to use a static field. There are no other possibilities, only this two.

AlexWien
  • 28,470
  • 6
  • 53
  • 83
  • My suspicion is that the error is arising because he's trying to compile a static inner class that references the variable. If that's the case, another option is to make the inner class non-static. – Hot Licks Jan 15 '13 at 12:24
  • If It's Static then I can't change from false to true. Meaning I can't Pause the game. – user1979117 Jan 15 '13 at 14:11
  • Of course you can change a static variable: static boolean isPaused; you only cannot change a static final field: static final int NUM_GAME_LEVELS = 30; – AlexWien Jan 15 '13 at 16:46
1

There is no such thing as a "global variable" in Java.

You could approach that behavior using a Singleton. A static field of a class will also give you similar behavior (though you ruled that option out in your question).

If you do not have multiple threads reading and writing the variable, and if psd should have one value across the entire application (which is implied by "global variable") I would indeed recommend making it static.

If each instance of the class it is declared in must have a separate copy of psd, I would instead suggest that fileItem5 must have a reference to the class psd is defined in, in order to be able to set it.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Actually, what's called "static" in Java is more like what would be considered "global" in other languages. Though the distinction is vague at best. – Hot Licks Jan 15 '13 at 03:37
  • 1
    @HotLicks - no the distinction is clear. A "global" has a name that is visible anywhere without qualification, and hence 1) can be hard to locate, and 2) can have colliding definitions. Java statics need to be qualified with the class name and hence don't suffer from those problems. (And indeed, statics don't need to be public in Java.) – Stephen C Jan 15 '13 at 03:46