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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19416446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:58:34  来源:igfitidea点击:

How do I access variables from the main class from another class (java)?

javaclassvariablesmethodsmain

提问by Chip Goon Lewin

I'm making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access from an ActionListener class. Here is some sample code from the ActionListener class. the the int variables (ex. clicks, grandamaCost) and the JTextFields (ex. display, cpsDisplay) are all in the main method. I was wondering how I could have access to variables in the main method so that this code could work in the other class. Thanks!

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

}

}

回答by Joel Christophel

Your variables should be fields.

您的变量应该是fields

Fields are declared outside of a class's methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.

字段在类的方法之外声明,通常位于类声明的正下方。字段可以被类的所有方法访问。

They can also be accessed from other classes (unless they are private) using the dot operator.

也可以使用点运算符从其他类(除非它们是私有的)访问它们。

  • If a field is marked with static, its class name is used to reference it.
  • If a field is not static, an object of its class is used to reference it.
  • 如果字段标有static,则使用其类名来引用它。
  • 如果字段不是静态的,则使用其类的对象来引用它。

Example

例子

    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
        }
    }

and another class...

和另一个班级...

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
    }
}

And to have more control over the access of your fields, you can use getters and setters. Take a read!

为了更好地控制字段的访问,您可以使用getter 和 setter。读一读!

回答by hthserhs

Using fields and their accessor methods. An example here.

使用字段及其访问器方法。这里有一个例子。

回答by dckuehn

You would have to make the variables public class variables instead of method variables, thereby increasing the scope and visiblity of the variables. Like so:

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

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

    @Override
    public void actionPerformed(ActionEvent e) {


        ...
    }
}

A more popular/recommended way to do this is to use a getter/setter instead of making the variable explicitly public. You would access a private variable through public methods like so:

一种更流行/推荐的方法是使用 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;
        }
    }
}

This way, you have more control over what your variables are set to.

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

回答by Shaban Mousa

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

}

}

回答by yushulx

You can pass main class instance reference to another class instance, or register callback. For the first way

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

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

For the second way 1. declare an interface 2. implement this interface in main class 3. register this implementation to another class. 4. get and set value in another class.

对于第二种方式 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);
        }
    }
}

回答by Ducksauce88

Here, I will give you an example for exactly what you need. In this code you simply just need to set anything you would like to add to actionPerformedas static.

在这里,我将为您提供一个示例,说明您需要什么。在这段代码中,您只需要设置您想要添加的任何内容actionPerformedas 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 

        }

    }

}