【问题标题】:How do I access variables from the main class from another class in the same project? [duplicate]如何从同一项目中的另一个类访问主类中的变量? [复制]
【发布时间】:2013-10-25 08:35:44
【问题描述】:

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

【问题讨论】:

标签: java class variables main


【解决方案1】:

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

private int clicks

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

public int getClicks() {
     return clicks;
}

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

然后你使用上面的方法获取和设置在任何类之外使用它

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 2020-11-17
    • 2013-10-25
    • 2017-02-24
    • 1970-01-01
    • 2023-04-07
    • 2020-11-24
    • 2017-03-22
    • 2011-10-22
    相关资源
    最近更新 更多