[英]Passing variables between classes in Java
I have two separate classes: GameOfLife.java
and Grid.java
, the latter of which has a paintComponent
method. 我有两个单独的类: GameOfLife.java
和Grid.java
,后者有一个paintComponent
方法。 In GameOfLife.java
, I have a constantly changing variable, toRepaint
, that I need to access in Grid.java
. 在GameOfLife.java
,我有一个不断变化的变量toRepaint
,我需要在Grid.java
访问Grid.java
。
Here is a section of GameOfLife.java
where I set toRepaint
: 这是GameOfLife.java
,我在其中设置了toRepaint
:
if (an==0) {
toRepaint = (String)c.getSelectedItem();
System.out.println(toRepaint);
}
main.repaint();
Here is where I need to access that variable in Grid.java
: 这是我需要在Grid.java
访问该变量的Grid.java
:
public void paintComponent(Graphics ob) {
super.paintComponent(ob);
Graphics2D g1 = (Graphics2D) ob;
String rep = ??? //This variable should equal the value of toRepaint
}
How can I access this variable? 我该如何访问这个变量?
My suggestion will be : 我的建议是:
public interface IGame{
String getName();
}
and override the method like 并覆盖类似的方法
@Override
public String getName(){
return rep;
}
public void paintComponent(Graphics ob) {
super.paintComponent(ob);
Graphics2D g1 = (Graphics2D) ob;
String rep = myInterface.getName();
}
To do this, you must make the variable you want to access in another class a public class variable (also known as a field): 为此,您必须使要在另一个类中访问的变量成为公共类变量(也称为字段):
public class GameOfLife{
public static String toRepaint;
public void yourMethod() {
//set value, do stuff here
}
}
And then in Grid.java, you access the class variable using dot syntax: 然后在Grid.java中,使用点语法访问类变量:
public void paintComponent(Graphics ob) {
super.paintComponent(ob);
Graphics2D g1 = (Graphics2D) ob;
String rep = GameOfLife.toRepaint;
}
HOWEVER 然而
This is not the best way to do it, but is by far the simplest. 这不是最好的方法,但到目前为止最简单。 In order to follow object-oriented programming we would add the following accessor method to our GameOfLife
class: 为了遵循面向对象的编程,我们将向GameOfLife
类添加以下访问器方法:
public static String getToRepaint(){
return toRepaint;
}
and change our variable declaration to: 并将我们的变量声明更改为:
private static String toRepaint;
In our Grid class, we instead call the method that accesses the toRepaint
variable: 在我们的Grid类中,我们改为调用访问toRepaint
变量的方法:
String rep = GameOfLife.getToRepaint();
This is the heart of object oriented programming, and although it seems redundant, can be quite helpful later on and will help keep code much neater. 这是面向对象编程的核心,尽管它似乎是多余的,但在以后可能会非常有用,并且有助于使代码更加整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.