Hoser
Hoser

Reputation: 5044

Add listener to a drop down menu

So I have a drop down menu built below:

new Label(shell, SWT.NONE).setText("Bet Type:");
betType = new Combo(shell, SWT.SINGLE | SWT.BORDER);
betType.setItems(new String[] {"   ", "NFL", "NBA", "CFB"});
betType.setLayoutData(gridData);

What I want is for when somebody selects one of the dropdown options, a function that I will write later will be called.

I've tried doing things like:

betType.addSelectionListener(new SelectionAdapter()) { ... }

Or:

betType.addSelectionListener(new SelectionListener()) { ... }

Or:

betType.addModifyListener(new ModifyListener()) { ... }

And I keep getting errors saying "Cannot Instantiate the type ModifyListener or SelectionListener" etc. How would one go about correcting this?

Upvotes: 0

Views: 1788

Answers (1)

Baz
Baz

Reputation: 36894

The problem with your code is that you close the first (-bracket too early.

This:

betType.addSelectionListener(new SelectionListener()) { ... }

should be:

betType.addSelectionListener(new SelectionListener() { ... });

The following code does exactly what you want:

public static void main(String[] args)
{
    Display d = new Display();
    final Shell shell = new Shell(d);
    shell.setLayout(new GridLayout(1, false));

    new Label(shell, SWT.NONE).setText("Bet type:");

    final Combo betType = new Combo(shell, SWT.SINGLE | SWT.BORDER);
    betType.setItems(new String[] {"   ", "NFL", "NBA", "CFB"});

    betType.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            System.out.println(betType.getText());
        }
    });


    shell.pack();
    shell.open();
    while (!shell.isDisposed())
        while (!d.readAndDispatch())
            d.sleep();
}

Alternatively, this works as well:

betType.addSelectionListener(new SelectionListener()
{
    @Override
    public void widgetSelected(SelectionEvent arg0)
    {
        System.out.println(betType.getText());
    }

    @Override
    public void widgetDefaultSelected(SelectionEvent arg0)
    {
    }
});

Upvotes: 3

Related Questions