我正在java中制作一个cookie clicker克隆来练习我的java技能,我有一个小问题,我在主类中声明了我想从ActionListener类访问的变量。以下是ActionListener类的一些示例代码。 int变量(例如clicks,grandamaCost)和JTextFields(例如display,cpsDisplay)都在主类中。我想知道如何访问主类中的变量,以便此代码可以在其他类中工作。谢谢!
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
button(b.getText());
}
/**
*
* @param input the label of the buttons being clicked.
*/
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;
}
}
答案 0 :(得分:1)
我实际上没有通过您的代码,但标准的方法是在主类中定义两个私有类变量
private int clicks
然后你定义setter和getters来设置它们并获取它们
public int getClicks() {
return clicks;
}
public int setClicks(int i) {
clicks = i;
}
然后使用上面的方法获取并设置在任何类
旁边使用它