0

I tested the Listener with a JButton and it worked, but I can't figure out why it wont do what I want with the combo box. I want it to perform a different action based upon the users selection from the combobox. e.g. when a user selects USA the expected behavior is to close the GUI window.

public class AccountListTest extends JFrame implements ActionListener{

    public JComboBox combo;

    AccountListTest()
    {
        JFrame myframe = new JFrame();
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mypanel = new JPanel();

        String [] country = {"USA","Ireland"};


        //JComboBox combo = new JComboBox();
        myframe.setSize(450,300);

        combo = new JComboBox(country);
        combo.addActionListener(this);

        mypanel.add(combo , BorderLayout.PAGE_END);

        myframe.add(mypanel);


        myframe.setVisible(true);
        AddressFactory afactory = new AddressFactory();

        //afactory.getAccountList(USA).display();
        //afactory.getAccountList(Ireland).display();

        combo.addActionListener(this);

        myframe.add(mypanel);
        myframe.setVisible(true);


    }


    public  static void main (String[] args)
    {
        new AccountListTest();

    }

    public void actionPerformed(ActionEvent e) {
        Object originator = e.getSource();

        if(e.getActionCommand().equals("USA"))
        {
            System.exit(0);
        }
        else if(e.getActionCommand().equals("Ireland"))
        {
            System.out.println("IRL SEL");
        }
        // TODO Auto-generated method stub

    }
}
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
A Kel
  • 75
  • 9
  • Possible duplicate of [JComboBox Selection Change Listener?](http://stackoverflow.com/questions/58939/jcombobox-selection-change-listener) – 3kings Feb 16 '16 at 21:35

1 Answers1

0

Try with getting the string of the combo when the actionPerformed is triggerd:

public void actionPerformed(ActionEvent e) {
        String selectedValue = combo.getSelectedValue().toString();
        if("USA".equalsIgnoreCase(selectedValue))
        {
            //Do Something for USA
        }
        else if("Ireland".equalsIgnoreCase(selectedValue))
        {
            //Do something irish
        }
        // TODO Auto-generated method stub

    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97