我正在用java做一个cookie clicker克隆来练习我的java技能,我有一个小问题,我有一个在main方法中声明的变量,我想要从一个ActionListener类访问这些变量。下面是来自ActionListener类的一些示例代码。整型变量(例如clicks、grandamaCost)和JTextFields (例如display、cpsDisplay)都在main方法中。我想知道如何才能访问main方法中的变量,以便此代码可以在其他类中工作。谢谢!
@Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
button(b.getText());
}
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;
}
}}
发布于 2013-10-17 08:54:02
你的变量应该是fields。
字段在类的方法之外声明,通常位于类声明的正下方。一个类的所有方法都可以访问字段。
也可以使用点运算符从其他类访问它们(除非它们是私有的)。
static,则其类名用于引用该字段。示例
public class Man {
public String name; //this is a field
public static String gender = "Male"; //this is a static field
public Man(String newName) {
name = newName; //assigns the value of a field from within a method
}
}另一个类..。
public class Main {
public static void main(String[] args) {
Man bob = new Man("Bob");
System.out.println(bob.name); //referenced from object, prints Bob
System.out.println(Man.gender); //referenced from class name, prints Male
}
}要更好地控制字段的访问,可以使用getters and setters。读一读吧!
发布于 2013-10-17 09:31:27
public class ActionClass {
{
private static int clicks;
@Override
public void actionPerformed(ActionEvent e) {
clicks++;
}
public static void setClicks(int c){
clicks = c;
}
public static int getClicks(){
return clicks;
}
}
public class AnyClass {
{
// now you have access to your clicks count .
int clicks = ActionClass.getClicks();
// set value of clicks
ActionClass.setClicks(0);}
发布于 2013-10-17 11:52:38
在这里,我将给你一个例子来说明你所需要的东西。在这段代码中,您只需将想要添加到actionPerformed的任何内容设置为static即可。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class testJava implements ActionListener {
protected static JButton b; // since this is static you can
// now access it in other classes
public static void main(String[] args) {
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == b) {
// do stuff here
}
}
}https://stackoverflow.com/questions/19416446
复制相似问题