I'm making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access from an ActionListener class. Here is some sample code from the ActionListener class. the the int variables (ex. clicks, grandamaCost) and the JTextFields (ex. display, cpsDisplay) are all in the main method. I was wondering how I could have access to variables in the main method so that this code could work in the other class. Thanks!
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
button(b.getText());
}
public void button(String input) {
switch (input) {
case "Cookie":
clicks++;
display.setText("Cookies: " + clicks + "");
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy grandma":
if (clicks >= grandmaCost) {
grandmas++;
clicks = clicks - grandmaCost;
grandmaCost = (int) ((.15 * grandmaCost) + grandmaCost);
cps++;
}
display.setText("Cookies: " + clicks + "");
prices[0].setText("$" + grandmaCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy monkey":
if (clicks >= monkeyCost) {
monkeys++;
clicks = clicks - monkeyCost;
monkeyCost = (int) ((.15 * monkeyCost) + monkeyCost);
cps = cps + 2;
}
display.setText("Cookies: " + clicks + "");
prices[1].setText("$" + monkeyCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy Teemo":
if (clicks >= teemoCost) {
teemos++;
clicks = clicks - teemoCost;
teemoCost = (int) ((.15 * teemoCost) + teemoCost);
cps = cps + 3;
}
display.setText("Cookies: " + clicks + "");
prices[2].setText("$" + teemoCost);
cpsDisplay.setText("CPS: " + cps);
break;
}
}
}
解决方案
Your variables should be fields.
Fields are declared outside of a class's methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.
They can also be accessed from other classes (unless they are private) using the dot operator.
If a field is marked with static, its class name is used to reference it.
If a field is not static, an object of its class is used to reference it.
Example
public class Man {
public String name; //this is a field
public static String gender = "Male"; //this is a static field
public Man(String newName) {
name = newName; //assigns the value of a field from within a method
}
}
and another class...
public class Main {
public static void main(String[] args) {
Man bob = new Man("Bob");
System.out.println(bob.name); //referenced from object, prints Bob
System.out.println(Man.gender); //referenced from class name, prints Male
}
}
And to have more control over the access of your fields, you can use getters and setters. Take a read!