There is such a method:

public void render(Graphics g) { g.setColor(Color.red); g.fillRect((int)x, (int)y, sizeX, sizeY); } 

And I want, instead of Color.red , I have a color variable, which I can access from any other class and change the color at any time. Is there a way to assign a Color.* Method to a variable?

  • one
    What kind of method is this about? Color.red is a java.awt.Color constant located in the same java.awt.Color class. Nobody forbids you to keep the field public Color color and assign it any color. And, of course, write g.setColor(color); . - Regent
  • @Regent well, misinterpreted the question, but the answer is exactly what you need, but how can I declare a new color in another class? Those. in class number 1, I write public Color color; Now I am writing g.setColor(color); And how can I change the color in another class? - Stab Ones

1 answer 1

Color.red is not a method, but a constant in the Color file. It looks like this:

 public final static Color red = new Color(255, 0, 0); 

Accordingly, it is sufficient to simply store the current color in a field of type Color .

Therefore, we add a public method to the class to set the color, store the set color in the field and use it when drawing.

As a result, the class looks like this:

 public class Entity { private Color color = Color.green; public void setColor(Color color) { this.color = color; } public void render(Graphics g) { g.setColor(color); } } 

And you can use it like this:

 Entity entity = new Entity(); entity.setColor(Color.red); entity.render(); Color newColor = new Color(200, 200, 200); entity.setColor(newColor); entity.render(); 

Using both "standard" colors (for example, Color.red ), and manually created ones (for example, new Color(200, 200, 200) ).