JComboBox上的监听器没有选择

时间:2021-07-16 23:13:07

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.

我用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

    }
}

1 个解决方案

#1


0  

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

尝试在触发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

    }

#1


0  

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

尝试在触发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

    }

相关文章