Help me on toolbar problem

Frank Benoit keinfarbton at googlemail.com
Fri Aug 8 05:03:20 PDT 2008


Sam Hu schrieb:
> Hi there,
> 
> I am reading SWT: A Developer's Notebook and tried some code in the book,sure I also tried to re-organize the structure and to see what happens.In the attached simple code,the Option menu,Window menu and toobar item CHECK does not work properly.When I click on it,the application quit immediatley.I don't know why.
> 
> Can anyboy help me?
> Thanks and best Regards,
> Sam

This is a difference between Java and D. In Java when you have a 'final' 
variable, you can access it from an anonymous class, because that 
variable is copied into that anonymouse class in a hidden way.

D does not do that.

In you example you have 'radioItem1' as a local variable of the method 
createMainMenu(). It does only exist for the duration of 
createMainMenu() execution. After that the variable storage is reused 
for other stuff. (The variable was located on the stack)
But the problem is, the SelectionListener uses the 'radioItem1' when the 
user clicks the menu. At this time the 'radioItem1' variable do no more 
exist.

To solve this problem you need to ensure, the SelectionListener uses a 
valid reference. Use one the following possibilities.

1.) Make radioItem1 a member variable of Form
2.) Make radioItem1 a global variable
3.) The widget is passed in the Event object
     MenuItem item = cast(MenuItem) event.widget;
4.) Copy the reference into the SelectionListener at creation of it:

radioItem1.addSelectionListener(new class(radioItem1) SelectionListener{
   MenuItem radioItem1_;
   this( MenuItem a){ radioItem1_=a; }
   public void widgetSelected(SelectionEvent e) {
     if(radioItem1_.getSelection) {
       MessageBox.showInfo("RadioItem1 is selected.","HaHA");
     }
   }
   public void widgetDefaultSelected(SelectionEvent e){}
});

5.) Not in this case, but for "Runnable" and "Listener" a template 
wrapper exist. See dgRunnable and dgListener.

Frank




More information about the Digitalmars-d-dwt mailing list