如何从另一个类(java)访问主类中的变量?

时间:2013-10-17 00:52:30

标签: java class variables methods main

我正在java中制作一个cookie clicker克隆来练习我的java技能,我有一个小问题,我有一些变量在main方法中声明,我想从ActionListener类访问。以下是ActionListener类的一些示例代码。 int变量(例如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;
    }
}

}

6 个答案:

答案 0 :(得分:9)

您的变量应为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。读一读!

答案 1 :(得分:3)

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);

}

答案 2 :(得分:1)

在这里,我将举例说明您的需求。在此代码中,您只需将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 

        }

    }

}

答案 3 :(得分:0)

使用字段及其访问器方法。示例here

答案 4 :(得分:0)

您必须使变量公共类变量而不是方法变量,从而增加变量的范围和可见性。像这样:

public class ActionClass {
{
    public string MyPublicVariable = "woot";

    @Override
    public void actionPerformed(ActionEvent e) {


        ...
    }
}

更流行/推荐的方法是使用getter / setter而不是明确公开变量。您可以通过公共方法访问私有变量,如:

public class ActionClass {
{
    @Override
    public void actionPerformed(ActionEvent e) {

        private string MyPublicVariable = "woot";

        public void setMyString(string newString){
            MyPublicVariable = newString;
        }

        public string getMyString(){
            return MyPublicVariable;
        }
    }
}

这样,您可以更好地控制变量的设置。

答案 5 :(得分:0)

您可以将主类实例引用传递给另一个类实例,或者注册回调。 第一种方式

Class MainClass {
  private int mValue;
  public void init() {
     AnotherClass cla = new AnotherClass(this); 
  }
  public void setValue(int value) {mValue = value;}
  public int getValue(){return mValue;}
}

Class AnotherClass {
  private MainClass mMain;
  public AnotherClass(MainClass ref) {
     mMain = ref;
  }

  public void controlValue() {
     if (mMain != null) {
        mMain.setValue(1);
        mMain.getValue();
     }
  }
}

第二种方式 1.声明一个接口 2.在主类中实现此接口 3.将此实现注册到另一个类。 4.在另一个类中获取并设置值。

public interface ClassListener {
    public void setValue(int value);
    public int getValue();
}

public class MainClass implements ClassListener{

    private int mValue;

    public void registerListener() {
        AnotherClass cla = new AnotherClass();
        cla.registerListener(this);
    }

    @Override
    public void setValue(int value) {
        // TODO Auto-generated method stub
        mValue = value;
    }

    @Override
    public int getValue() {
        // TODO Auto-generated method stub
        return mValue;
    }
}

public class AnotherClass{

    private ClassListener mListener;

    public void registerListener(ClassListener listener) {
        mListener = listener;
    }

    public void controlValue() {
        if (mListener != null) {
            int value = mListener.getValue();
            mListener.setValue(++value);
        }
    }
}