2013-03-06 29 views
2

我有一個確定按鈕(按鈕)創建。如何動態創建SWT按鈕及其操作?

基於用戶輸入,我想動態創建1到10個SWT按鈕(複選框)。

如何創建它?

如果確定按鈕被點擊,如何顯示哪些是全部複選框按鈕已被選中?

請看以下代碼片段我,試圖:

Set<String> Groups = getData(Contents); 
for(String group : contentGroups) { 

contentButton = new Button(fComposite, SWT.CHECK); 

    // is this right way to create dynamic buttons? 

    contentButton.setText(group); 

} 

okButton = new Button(lowComposite, SWT.PUSH); 

okButton.addSelectionListener(new SelectionListener(){ 

    @Override 
    public void widgetSelected(SelectionEvent e){ 

     //Here how to get the selection status of contentButtons?  
    } 
} 
+0

您必須保存'Button's在'最後'或'靜態''List'能夠訪問它們/在'Listener'中迭代它們。 – Baz 2013-03-06 10:31:51

+0

但是如何保存和迭代?如何獲取所有contentButtons的變量名?ok按鈕和複選框是在不同的複合材料中創建的。請給出一些片段。 – yash 2013-03-06 10:33:46

回答

4

這將打印出的按鈕的選擇狀態:

Set<String> Groups = getData(Contents); 

final List<Button> buttons = new ArrayList<Button>(); 

for(String group : contentGroups) 
{ 
    Button newButton = new Button(fComposite, SWT.CHECK); 
    newButton.setText(group); 

    // save the button 
    buttons.add(newButton); 
} 

Button okButton = new Button(lowComposite, SWT.PUSH); 

okButton.addListener(SWT.Selection, new Listener() 
{ 
    @Override 
    public void handleEvent(Event e) 
    { 
     // iterate over saved buttons 
     for(Button button : buttons) 
     { 
      System.out.println(button.getText() + ": " + button.getSelection()); 
     }  
    } 
} 
+0

非常感謝您的摘錄。它適用於我:) – yash 2013-03-07 04:12:21

+0

我做到了。其顯示投票需要15聲望... – yash 2013-03-07 09:56:21

+0

@yash現在你有15;) – Baz 2013-03-07 09:57:27