确保JCombo操作仅在初始选择时执行?

时间:2015-12-11 19:47:14

标签: java swing jcombobox

我需要使用JCombo盒子,目前我只是将消息打印到屏幕上进行测试。当我做出选择它按预期工作,但是当我然后重新单击组合框以更改选择时,我得到相同的消息框,然后让我做出另一个选择。如何才能获得该操作以便仅在初始选择时执行操作?

   String[] positions={"1","2","3","4"};
    JComboBox combo = new JComboBox<String>(positions);
    combo.addActionListener(new ActionListener(){

          @Override
          public void actionPerformed(ActionEvent ae ){
              //Display selected stuff
              JOptionPane.showMessageDialog(null, combo.getSelectedItem());

          } 
    });

3 个答案:

答案 0 :(得分:3)

使用boolean了解是否已经检查过。

解决方案

String[] positions={"1","2","3","4"};
JComboBox combo = new JComboBox<String>(positions);
combo.addActionListener(new ActionListener(){
      boolean comboAlreadyChecked = false;

      @Override
      public void actionPerformed(ActionEvent ae ){
          //Display selected stuff
          if (!comboAlreadyChecked){
              JOptionPane.showMessageDialog(null, combo.getSelectedItem());
              comboAlreadyChecked = true;
          }
      } 
});

PS:布尔值的名称可能比这个稍微容易一些。这只是为了澄清。

答案 1 :(得分:2)

在接受所提供的答案并通过修改上述教程中给出的解决方案后,我提出了以下解决方案:

String labels[] = {"", "A", "B", "C", "D", "E", "F"};
JComboBox comboBox = new JComboBox(labels);
ItemListener itemListener = new ItemListener() {
    public void itemStateChanged(ItemEvent itemEvent) {
        int state = itemEvent.getStateChange();
        ItemSelectable is = itemEvent.getItemSelectable();
        if (selectedString(is) == "A" & state == ItemEvent.SELECTED) {
            System.out.println("A");
        }
    }
};
comboBox.addItemListener(itemListener);

答案 2 :(得分:1)

请试试这个

  public static void main(String args[]) {

        JComboBox comboBox = new JComboBox();

        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                System.err.println("new item: " + e.getItem());
            }
        });
    }