2016-02-16 42 views
0

我測試ListenerJButton它的工作,但我不明白爲什麼它不會做我想要的組合框。我希望它根據用戶從組合框中的選擇執行不同的操作。例如當用戶選擇USA時,預期的行爲是關閉GUI窗口。JComboBox上的聽衆沒有選擇選項

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 

    } 
} 
+0

可能重複的[?JComboBox的選擇更改偵聽器(http://stackoverflow.com/questions/58939/ jcombobox-selection-change-listener) – 3kings

回答

0

嘗試獲得組合的字符串時actionPerformed是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 

    } 
+0

完美作品非常感謝 –