0

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?

4 Answers 4

1

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.

1
  • 2
    Not quite. It needs to be s.color = new Color(r, 0, 0)
    – Tesseract
    Dec 8, 2012 at 20:41
1

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.

1
  • 2
    Even if Color was mutable, changing the value of r wouldn't change anything to the color. The problem is not immutability, but pass by value vs. pass by reference.
    – JB Nizet
    Dec 8, 2012 at 20:21
1

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.