0

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

1 回答 1

1

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

private int clicks

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

public int getClicks() {
     return clicks;
}

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

然后您使用上述方法获取并设置在任何类之外使用它

于 2013-10-17T01:38:04.463 回答