JComboBox 上的侦听器未拾取选择



我用JButton测试了Listener并且它起作用了,但我无法弄清楚为什么它不能用组合框做我想做的事情。我希望它根据用户从组合框中选择执行不同的操作。例如,当用户选择USA时,预期的行为是关闭 GUI 窗口。

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
    }
}
尝试在

触发actionPerformed时获取组合的字符串:

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
    }

最新更新