Search code examples
javaswtccombobox

How to add objects to CComboBox


I have declared my CComboBox as follows :

     final CCombo combobox= new CCombo(shell, SWT.BORDER);
     combobox.setBounds(30, 22, 88, 21);

     ResultSet result = statement.executeQuery();

I want to add an object of Class myCombo to combobox

     while(result.next())
     {
          String ProName=result.getString(1);
          String ProId=result.getString(2);
          myCombo comboItem=new myCombo(ProId,ProName); //OBJECT comboItem
          combobox.addElement(comboItem); //ERROR The method addElement(myCombo)  
                                             is undefined for the type CCombo
      } 

Error in combobox.addElement(comboItem) .... but addElement() is already defined in CCombo.

This is class myCombo

class myCombo{
               private String ProId;
               private String ProName;


               public myCombo(String ProId, String ProName) {
                   this.ProId=ProId;
                   this.ProName=ProName;

               }

               public String getProductName() {
                      return ProName;
                   }

               public String getProductId() {
                      return ProId;
                   }

                   @Override
               public String toString() {
                      return ProName;
               }
        }

How to get back the data which is selected.
Showing ERROR as cant

combobox.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {



    myCombo item = (myCombo) combo.getItem(getSelectionIndex()) ; //ERROR

                    if (item!=null) {
                       System.out.printf("You've selected Product Name: %s, Product ID: %s%n", 
                             item.getProductName(), item.getProductId());
                    }

            }
        });

Solution

  • If you are using org.eclipse.swt.custom.CCombo than it does't have addElement(Object o) method.It has add(String s) method you have to override toString().

          myCombo comboItem=new myCombo(ProId,ProName); 
          combobox.add(comboItem.toString())
    

    FOR EXAMPLE

               @Override
               public String toString() {
                      return ProId+":"+ProName;
               }
    

    TO Fetch Selection,

      combo.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                System.out.print("Selected Value-");
                System.out.print(combo.getItem(combo.getSelectionIndex()));
            }
        });