Question

Ok, so here is the problem: Every time I click OK it should return the selected index number, right? The code below is returning ONLY the first index regardless of what I select. I set "cMenu.selected(1)" and it returns index 1, again, regardless of what I select.

Using JPanel, JButton, Choice

String[] menu = {"item 1" , "item 2", "item3"};

cMenu = new Choice();
cMenu.setBounds(0, 0, 75, 25);
for (int i = 0; i < menu.length; i++)
    cMenu.add(menu[i]);
}
panel.add(cMenu);

final int menuSelection = cMenu.getSelectedIndex();

//Below is, of course, debugging
//Before asking, the button works it does say 0 or Hello World or whatever I want
//when clicked

OK.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println(menuSelection);
    }
});
Was it helpful?

Solution

You need to recalculate the value for menuSelection when the 'OK' button is clicked; you're setting it once during instantiation of the Choice as shown below:

final int menuSelection = cMenu.getSelectedIndex();

If you do something like this, you should be able to see your value:

OK.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int currentSelection = cMenu.getSelectedIndex();
        System.out.println(currentSelection);
    }
});

This will mean cMenu should be final, which is probably OK because you don't need to ever update that reference.

OTHER TIPS

"OK it should return the selected index number". No, it should not. you're calling getSelectedIndex() once. So your int has the same value forever. You have to call getSelectedIndex() in your listener to get the new value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top