Reputation: 2652
I have created a program in Java ( for exercise purposes) and I have a star where the color must go from lightred to dark red by scrolling the mouse.. ( using the MouseWheelListener ) and vica versa Everything works well with other kind of stars but only this one doesn't work.. instead of confusing you guys, i'm gonna show you some code!
here is the red star class
public class StarRed extends Star {
protected int r = 221;
protected Color rood = new Color(r, 0, 0);
public StarRed(int radius, int x, int y) {
super(radius, x, y);
this.color = rood;
System.out.println(r);
}
}
as you see I have tried to use the R variable to change the color..
in my controller I do this
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
for(StarRed s: rs) {
s.r += e.getWheelRotation();
}
repaint();
}
but the color doesn't change, can anyone tell me what i'm doing wrong?
Upvotes: 0
Views: 2262
Reputation: 5867
You need to instantiate a new color each time you move the wheel, like this:
for(StarRed s: rs) {
s.r += e.getWheelRotation();
s.rood = new Color(r, 0, 0);
s.color = s.rood;
}
Currently you are only changing the field r
, and not the Color rood
that r
was used to construct.
Upvotes: 1
Reputation: 692271
When you pass a variable of type int
(or any other primitive type) to a method or constructor, you pass the value of the variable (a copy if you prefer). You don't pass a reference to its value. So changing the value of the variable won't change anything to the Color you created with previously this variable.
You need to mutate the color object (but this is impossible bacause Color is immutable), or replace the color object itself with another one.
Upvotes: 1
Reputation: 1365
Assuming that you've implemented the mouseWheelMoved correctly, the issue lies when you are adding to the value r.
Although rood is:
protected Color rood = new Color(r, 0, 0);
When you change the value of r
after you've created the color, it will not change the value of the red part of your Color rood
.
So instead, you want to make a function that adds to the red value of your Color rood and then changes the Color itself.
Upvotes: 1
Reputation: 12843
The Color is immutable class, changing value of r does not change the value of protected Color rood
So what you need to do is add new method in your star class where the value of rood i.e color to use is changed based on given parameters.
Upvotes: 1