gpt4 book ai didi

java - 如何从同一项目中的另一个类访问主类的变量?

转载 作者:行者123 更新时间:2023-12-01 13:59:35 32 4
gpt4 key购买 nike

我正在用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;
}
}

最佳答案

我实际上并没有查看您的代码,但执行此操作的标准方法是在主类中定义两个私有(private)类变量

private int clicks

然后定义 setter 和 getter 来设置和获取它们

public int getClicks() {
return clicks;
}

public int setClicks(int i) {
clicks = i;
}

然后使用上述方法来获取和设置以在任何类之外使用它

关于java - 如何从同一项目中的另一个类访问主类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416811/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com