How to use .mouseDownAction and .mouseUpAction with a Button?

I am trying to use .mouseDownAction with a Button and am running into some difficulties.

My button has 4 states and I would like the state to stay unchanged when I click on it with the mouse. However, when I use the following code the state still goes +1 and then it stays constant:

(
w = Window.new("Example");

b = Button(w, Rect(90, 20, 200, 30))
        .states_([
            ["sine", Color.black, Color.rand],
            ["saw", Color.black, Color.rand],
            ["noise", Color.black, Color.rand],
            ["pulse", Color.black, Color.rand]
        ])
        .mouseDownAction_({ arg butt;
	butt.value = butt.value - 1;
            butt.value.postln;

        });
w.front;
)

The reason I am doing this is because I am using .keyDownAction to control the buttons and would not like the buttons to change when clicked on with a mouse.

Updating this question:

I found that if I update the following line:
butt.value = butt.value - 1;
to
butt.value = 3;

This prevents the button from advancing states if b.value = 0.
However if I am on a state < 0, it does not work anymore.

Thank you!

Instead of a Button, it might be easier to use a UserView and change the drawFunc in the
keyDownAction to display the correct text. For example:

(
w = Window.new("Example");

b = UserView(w, Rect(90, 20, 200, 30))
.drawFunc_({arg view;
	Pen.color = Color.black;
	Pen.stringCenteredIn("sine", Rect(0, 0, 200, 30));
})
.background_(Color.rand)
.keyDownAction_({|doc, char, mod, unicode, keycode, key|
	case
	{ char == $a }   {
		b.drawFunc_({arg view;
			Pen.color = Color.black;
			Pen.stringCenteredIn("sine", Rect(0, 0, 200, 30));
		})
		.background_(Color.rand);
		b.refresh;
	}
	{ char == $b }   {
		b.drawFunc_({arg view;
			Pen.color = Color.black;
			Pen.stringCenteredIn("saw", Rect(0, 0, 200, 30));
		})
		.background_(Color.rand);
		b.refresh;
	}
	{ char == $c }   {
		b.drawFunc_({arg view;
			Pen.color = Color.black;
			Pen.stringCenteredIn("noise", Rect(0, 0, 200, 30));
		})
		.background_(Color.rand);
		b.refresh;
	}
	{ char == $d }   {
		b.drawFunc_({arg view;
			Pen.color = Color.black;
			Pen.stringCenteredIn("pulse", Rect(0, 0, 200, 30));
		})
		.background_(Color.rand);
		b.refresh;
	}
});
w.front;
)

Best,
Paul

1 Like

@TXMod

Yes!! This is exactly what I am trying to achieve. I think I will go with this approach. Thank you.

On a side note, if anyone ever runs into the button issue, I did just come across a wonky way to achieve it:

For the button in the original question with 4 states, this will prevent the button from changing states no matter the state it is in.

b.mouseDownAction_({ arg butt;
	"down".postln;
x = case
	{b.value == 0}{'0'.postln; b.value = 3}
	{b.value == 1}{'1'.postln; b.value = b.value - 2}
	{b.value == 2}{'2'.postln; b.value = b.value - 1}
	{b.value == 3}{'3'.postln; b.value = b.value - 1};
});
w.front;
)