【问题标题】:[JAVA]How to call the method "itemStateChanged"[JAVA]如何调用方法“itemStateChanged”
【发布时间】:2015-07-03 06:16:17
【问题描述】:

所以,我有这个方法;

public void itemStateChanged(ItemEvent event){
        if(event.getSource() == temasJogo){
            if(event.getStateChange() == ItemEvent.SELECTED){
                indiceTema = indiceTemas[ temasJogo.getSelectedIndex() ];
            }

        }
    }

只为这个JComboBox

temasJogo = new JComboBox(temas);
        temasJogo.addActionListener(this);

我需要它来修改我的类的属性,以便它选择游戏的另一个主题。问题是,我无法在任何地方调用此方法。我知道答案会很简单,但我真的需要帮助。

【问题讨论】:

    标签: java swing jcombobox itemlistener


    【解决方案1】:

    理论上,itemStateChangedItemListener 的一个方法,假设您已经以某种方式实现了interface

    为了调用它,您需要使用JComboBox 注册ItemListener 的实例

    temasJogo.addItemListener(this);
    

    举个例子

    请参阅How to Use Combo BoxesHow to Write an Item Listener 了解更多详情

    【讨论】:

    • 我知道这很愚蠢,我使用了一个 ActionListener,即使它是一个 ItemListener。非常感谢!
    • 总是小事 ;)
    【解决方案2】:

    只在一个类中实现接口。

    例如

    class sample implements ItemListener
    

    在 JComboBox 上应用监听器

            temasJogo = new JComboBox(temas);
            temasJogo.addItemListener(this);
    

    之后,当item改变时会调用下面的函数。

    public void itemStateChanged(ItemEvent event){
            if(event.getSource() == temasJogo){
                if(event.getStateChange() == ItemEvent.SELECTED){
                    indiceTema = indiceTemas[ temasJogo.getSelectedIndex() ];
                }
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多