Slider Help

3 replies [Last post]
deepblue's picture
Offline
Joined: 01/06/2011

I'm unsure whether or not my ChangeListener is correct. Can someone take a look? I took out Fox's ability to die to see it better.
Here's my code:
UI CLASS:
JSlider foxBirth = new JSlider(K_MIN, K_MAX, K_INIT);
foxBirth.setMajorTickSpacing(20);
foxBirth.setPaintTicks(true);
foxBirth.setPaintLabels(true);
 
public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider)e.getSource();
        double newK = source.getValue();
        game.changeK(newK/100);
}
 
GAME CLASS:
public void changeK(double newK)
{
        k = newK;
}
 
for (Creature c : creatures)
{
                c.move(creatures, dead_creatures, new_creatures, k);
                env.addObject(c);
}
 
 
 
 

Offline
Joined: 12/13/2010
Change game.changeK(newK/100)

Change
game.changeK(newK/100);
to
game.changeK(newK/100.0);
 
In Java, when you do arithmetic with integers, you get an integer result.  When we force one of the operand to be a double, the result will be a double.

KMacKenzie's picture
Offline
Joined: 12/10/2010
You need to add the change

You need to add the change listener to the slider, right now the slider doesn't do anything.
Like we learned in class there are three ways to do this, you can either make a listener class specifically for each slider (longest way) or you can make a change listener method in the UI class and do something like
foxBirth.addChangeListener(this);
but your probably best off doing it the more sensible way and writing the method right into the slider like this...
foxBirth.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
        JSlider source = (JSlider)e.getSource();
        double newK = source.getValue();
        game.changeK(newK/100);
}

);
 
To test to see if its working properly in game just put a env.setDisplayStr(k); in your main play loop.
 

deepblue's picture
Offline
Joined: 01/06/2011
Ah! So though the only thing

Ah! So though the only thing I was missing was adding the ChangeListener? I wanted to first make it just a method at the bottom (where UI implements ChangeListener) and then do an anonymous inner class when I figured it out.
Thank you sir, you are a gentleman and a scholar.