Java 组合框中的项目

Java 组合框中的项目,java,combobox,Java,Combobox,当选择组合框中的某个项目时,我将执行和操作,但无论选择哪个项目,它都会执行操作。有人能帮我吗 //number of players combo box players = new JComboBox(); contentPane.add(players, BorderLayout.SOUTH); players.addItem("1 Player"); players.addItem("2 Players"); p

当选择组合框中的某个项目时,我将执行和操作,但无论选择哪个项目,它都会执行操作。有人能帮我吗

//number of players combo box
        players = new JComboBox();
        contentPane.add(players, BorderLayout.SOUTH);
        players.addItem("1 Player");
        players.addItem("2 Players");
        players.addActionListener(new ActionListener() {

         @Override
        public void actionPerformed(ActionEvent e) {
         makeFrame();
        }
       });
       players.addItem("3 Players");
//end of combo box

为了根据所选项目更改行为,您需要在
ActionListener
中检索所选值,并根据所选值更改行为。您可以使用以下内容:

//number of players combo box
//notice that you have to declare players
//as final. If it is a member of the class,
//you can declare it final in the field
//declaration and initialize it in the
//constructor, or if local, just leave it
//as it is here. Unless using Java 8, then it
//doesn't need to be declared final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String selectedValue = String.valueOf(players.getSelectedItem());
        if (selectedValue != null && (selectedValue.equals("1 Player") || selectedValue.equals("2 Players"))) {
            makeFrame();
        }
        else {
            //do something else
        }
    }
});
//end of combo box
如果您碰巧提前知道索引(即静态初始化选项列表,而不是动态生成列表),您也可以只参考以下内容检索索引:

//number of players combo box
//the combo box still needs to be final here
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int myIndex = players.getSelectedIndex();
        if (myIndex == 0 || myIndex == 1) {
            makeFrame();
        }
        else {
            //do something else
        }
    }
});
//end of combo box

你想要什么?如果值为1或2名玩家,您需要调用
makeFrame
。您需要确定选择了哪个项目,并根据该信息执行所需操作。当字段中的选定项发生更改时,将执行ActionPerformed…是的,如果选择了项2,则我希望生成框架()。。而不仅仅是当其他物品selected@user3507763“项目2”是指列表中的第二个项目(仍然是
“2名玩家”
)还是索引2中的项目(
“3名玩家”