ComboBox中的项目

时间:2014-04-07 21:03:03

标签: java combobox

当选择组合框中的项目时,我想要执行并执行操作,但无论选择哪个项目,它都会执行操作。有人可以帮我解决。

//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

1 个答案:

答案 0 :(得分:2)

为了根据选择的项目更改行为,您需要在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

如果您恰好提前知道索引(即,您静态初始化选项列表而不是动态生成列表),您还可以引用.getSelectedIndex()来检索索引,如下所示:< / p>

//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