B4J Question [SOLVED] Why would a button send the information for a previously clicked button?

Zeppah

Member
I have five buttons that use an event. The event is to change the colors of the buttons and to set the user's choice. One of the buttons is sending the information as if it is the last button that was selected. I am plum out of ideas.
B4X: Copy
'I have five buttons that use this event, four work and one button only sends
'The information for the last button pressed
'Button All is not changing the Sender, it is sending the code for the last button pressed
'
Sub PracticeMode_Click
    Log(Sender)
    CSSUtils.SetBackgroundColor(OldButton, fx.Colors.White)
    CSSUtils.SetBackgroundColor(Sender, fx.Colors.LightGray)
    OldButton = Sender
    PracticeNumber = OldButton.Tag
End Sub
 
Last edited:
It is a bit difficult to explain this one. Button is a "wrapper" object. The problem happens because you mix the assignments of OldButton with both the exact type and the non-exact type:
Code: Copy
OldButton = btnAll
'and later:
OldButton = Sender

It will work properly if you change it to:
Code: Copy
Sub PracticeMode_Click
    Dim btn As Button = Sender
    CSSUtils.SetBackgroundColor(OldButton, fx.Colors.White)
    CSSUtils.SetBackgroundColor(btn, fx.Colors.LightGray)
    OldButton = btn
    PracticeNumber = OldButton.Tag
End Sub
Or Dim OldButton before you assign it:
Code: Copy
Dim OldButton As Button = Sender
 
Upvote 0
The problem starts here:
Code: Copy
OldButton = btnAll
As both objects are of the same type, a new wrapper is not created. This means that both variables now point to the same wrapper.

Later the wrapper inner object is set:
Code: Copy
OldButton = Sender
Now btnAll actually points to the wrong button.

I might change the behavior of wrapper to wrapper assignments at some point to avoid this issue. Need to carefully check that there aren't other side effects for such change.
 
Upvote 0
I might change the behavior of wrapper to wrapper assignments at some point to avoid this issue. Need to carefully check that there aren't other side effects for such change.
I've been thinking about this - that's dangerous I know. :D
As both objects are of the same type, a new wrapper is not created
This is what I peronally would expect. An assignment of same type objects looks like a reference assignment so they are both the same object.

If the objects are of different types then a new wrapper could be created. This means cross-type assignments effectively become copy operations which seems reasonable as being different types I wouldn't expect them to necessarily point to the same object.
 
Upvote 0
Thank you very much Erel! I am fairly new to programming so I don't understand wrappers (yet) but I will definitely research them now. :)
Your fix worked properly just as you said it would.
 
Upvote 0
Back
Top