2013-07-01 52 views
0

我想在多個表(SWT表)上添加相同的菜單。當用戶點擊菜單項時,我想檢測與該菜單關聯的表。這是下面的代碼。將菜單添加到SWT表

private void setMenu(Table table) { 
     Listener popUpListener = new Listener() { 

      @Override 
      public void handleEvent(Event event) { 
       MenuItem item = (MenuItem)event.widget; 
       Menu pare = item.getParent(); 
       Decorations fdf = pare.getParent(); 
            //Code to get table name or instance of table. 

      } 
     }; 
     Menu menu = new Menu(table); // where table1 is your table 
     MenuItem item1 = new MenuItem(menu, SWT.PUSH); 
     item1.setText("Copy cell"); 
     item1.addListener(SWT.Selection, popUpListener); 
     MenuItem item2 = new MenuItem(menu, SWT.PUSH); 
     item2.setText("Copy row"); 
     item2.addListener(SWT.Selection, popUpListener); 
     MenuItem item3 = new MenuItem(menu, SWT.PUSH); 
     item3.setText("Copy column"); 
     item3.addListener(SWT.Selection, popUpListener); 
     MenuItem item4 = new MenuItem(menu, SWT.PUSH); 
     item4.setText("Copy all"); 
     item4.addListener(SWT.Selection, popUpListener); 
     table.setMenu(menu); 
    } 

setMenu方法被多次調用發送表的實例。 如何檢測與彈出監聽器中當前彈出菜單相關的表格。

回答

0

只是讓你Table發送到方法final

private void setMenu(final Table table) { 
    Listener popUpListener = new Listener() { 

     @Override 
     public void handleEvent(Event event) { 
      MenuItem item = (MenuItem)event.widget; 
      Menu pare = item.getParent(); 
      Decorations fdf = pare.getParent(); 

      // Now you can access the table from within the Listener 
      System.out.println(table); 
     } 
    }; 
    Menu menu = new Menu(table); // where table1 is your table 
    MenuItem item1 = new MenuItem(menu, SWT.PUSH); 
    item1.setText("Copy cell"); 
    item1.addListener(SWT.Selection, popUpListener); 
    MenuItem item2 = new MenuItem(menu, SWT.PUSH); 
    item2.setText("Copy row"); 
    item2.addListener(SWT.Selection, popUpListener); 
    MenuItem item3 = new MenuItem(menu, SWT.PUSH); 
    item3.setText("Copy column"); 
    item3.addListener(SWT.Selection, popUpListener); 
    MenuItem item4 = new MenuItem(menu, SWT.PUSH); 
    item4.setText("Copy all"); 
    item4.addListener(SWT.Selection, popUpListener); 
    table.setMenu(menu); 
}