JComboBox 上的侦听器未拾取选择
Listener on JComboBox not picking up selection
我用 JButton
测试了 Listener
并且它有效,但我不明白为什么它不能用组合框做我想做的事情。我希望它根据用户从组合框中的选择执行不同的操作。例如当用户选择 USA
时,预期的行为是关闭 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
}
}
尝试在触发 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
}
我用 JButton
测试了 Listener
并且它有效,但我不明白为什么它不能用组合框做我想做的事情。我希望它根据用户从组合框中的选择执行不同的操作。例如当用户选择 USA
时,预期的行为是关闭 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
}
}
尝试在触发 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
}