我正在 java 中制作一个 cookie 点击器克隆来练习我的 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;
}
}