Search code examples
javaeclipseeclipse-pluginswteclipse-rcp

Getting value of selected item in combo box eclipse plugin


How do I get the value of the selected item from a combo box? I keep getting a null pointer exception when executing the saveInput method.

Here is my dialog code:

public class MyTitleAreaDialog extends TitleAreaDialog {

    private String age;    
    private Combo combo;    

    public MyTitleAreaDialog(Shell parentShell) {
        super(parentShell);
    }

    @Override
    public void create() {
        super.create();
        setTitle("Age Box");
        setMessage("Please enter your info..", IMessageProvider.INFORMATION);
    }

    @Override
    protected Control createDialogArea(Composite parent) {            
        Combo combo = new Combo(container, SWT.READ_ONLY);
        combo.setItems(new String[] {"21", "22", "23"});    
        return area;
    }

    private void saveInput() {        
        if(combo.getSelectionIndex() >= 0){
            age = combo.getItem(combo.getSelectionIndex());
        }        
    }

    @Override
    protected void okPressed() {
        saveInput();
        super.okPressed();
    }

    public String getSelectedAge() {
        return age;
    }        
}

Here is the handler code:

public class SampleHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

        MyTitleAreaDialog dialog = new MyTitleAreaDialog(window.getShell());

        dialog.create();
        if (dialog.open() == Window.OK) {           
            System.out.println(dialog.getSelectedAge());            
        }       
        return null;
    }
}

I would appreciate any help..I'm new to Java and eclipse programming...thanks!!


Solution

  • Your createDialogArea method is assigning the Combo to a local variable called combo, not the field called combo.

    Replace:

    Combo combo = new Combo(container, SWT.READ_ONLY);
    

    with

    combo = new Combo(container, SWT.READ_ONLY);