I have two separate classes: GameOfLife.java
and Grid.java
, the latter of which has a paintComponent
method. In GameOfLife.java
, I have a constantly changing variable, toRepaint
, that I need to access in Grid.java
.
Here is a section of GameOfLife.java
where I set 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
:
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?
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:
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:
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:
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.