如何将对象添加到CComboBox

时间:2014-07-10 13:12:09

标签: java swt ccombobox

我已将我的CComboBox声明如下:

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

     ResultSet result = statement.executeQuery();

我想将类myCombo的对象添加到组合框

     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
      } 

组合框错误。 addElement (comboItem)....但是已经在CCombo中定义了addElement()。

这是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;
               }
        }

如何取回所选数据 将ERROR显示为不能

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());
                    }

            }
        });

1 个答案:

答案 0 :(得分:2)

如果您使用org.eclipse.swt.custom.CCombo而不是addElement(Object o)方法,则必须使用add(String s)方法覆盖 toString()

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

例如

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

获取选择,

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